Java--JDBC连接MySQL

Posted lvbl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java--JDBC连接MySQL相关的知识,希望对你有一定的参考价值。

//导入驱动包

package DatabaseT;
import java.sql.*;
import com.mysql.jdbc.Connection;

public class MysqlDemo {
    static final String DB_URL = "jdbc:mysql://localhost:3306/ch09?useSSL=false";
    // MySQL的JDBCURL编写方式:jdbc:mysql://主机名称:连接端口/数据库的名称
    static final String USER = "root";
    static final String PASS = "root";

    public static void main(String[] args) throws SQLException,Exception{
       Connection conn = null;
       PreparedStatement stat = null;

       // 注册驱动
       Class.forName("com.mysql.jdbc.Driver");

       // 创建链接
       conn = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);

       // 执行查询
       //stat = conn.createStatement();
       stat = conn.prepareStatement(DB_URL);
       String sql = "SELECT * FROM users";
       ResultSet rs = stat.executeQuery(sql);
       // 输出查询结果
       while(rs.next()){
           System.out.print(rs.getInt("id")+",");
           System.out.print(rs.getString("username")+",");
           System.out.print(rs.getString("password")+",");
           System.out.print(rs.getString("nickname"));
           System.out.print(" ");
       }
       // 关闭
      try {
          if (rs != null) {
              rs.close();
          }
      } catch (SQLException e) {
          e.printStackTrace();
      } finally {
          try {
              if (stat != null) {
                  stat.close();
              }
          } catch (SQLException e) {
              e.printStackTrace();
          } finally {
              try {
                  if (conn != null) {
                      conn.close();
                  }
              } catch (SQLException e) {
                  e.printStackTrace();
              }
          }
      }
    }
}



























































以上是关于Java--JDBC连接MySQL的主要内容,如果未能解决你的问题,请参考以下文章

Java JDBC连接MySQL

Java--JDBC连接MySQL

java jdbc连接

java jdbc与odbc数据库的连接mysql数据库

java JDBC连接mysql

Java JDBC连接MYsql