IDEA连接MySQL
package sun;
import java.sql.*;
public class MySqlDemo {
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/JavaTest?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
static final String USER = "root";
static final String PASSWORD = "root";
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
// 注册JDBC驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库。。。");
connection = DriverManager.getConnection(DB_URL,USER,PASSWORD);
// 执行查询
System.out.println("实例化Statement。。。");
statement = connection.createStatement();
String sql;
sql = "select * from JavaTest.student";
ResultSet resultSet = statement.executeQuery(sql);
// 展开结果数据集
while (resultSet.next()){
// 通过字段检索
int id = resultSet.getInt("id");
int studentId = resultSet.getInt("student_id");
String name = resultSet.getString("student_name");
String sex = resultSet.getString("student_sex");
// 输出数据
System.out.println("id:"+id+" studentId:"+studentId+" name:"+name+" sex:"+sex);
}
// 完成后关闭
resultSet.close();
statement.close();
connection.close();
} catch (Exception e){
e.printStackTrace();
} finally {
try {
if (statement!=null){
statement.close();
}
}catch (SQLException ignored){
}
try {
if (connection!=null){
connection.close();
}
}catch (SQLException ignored){
}
}
System.out.println("GoodBye!");
}
}
结果
连接数据库。。。
实例化Statement。。。
id:1 studentId:1001 name:张三 sex:男
id:2 studentId:1002 name:李四 sex:男
GoodBye!