IDEA连接数据库教程
首先我们新建一个项目,一直往下点就可以了
这里我们连接数据库的话需要8个步骤
1.导入jar包
把mysql-connector-java-8.0.15.jar复制导入刚刚创建的项目的src里面
2.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
3.获取数据库连接对象(localhost:3306/****? * 号写的是你的数据库名)
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?"
+ "useUnicode=true&characterEncoding=utf8&"
+ "useSSL=false&serverTimezone=Hongkong"
, "root", "123456");
4.定义sql语句(如一些简单的增删改查)
String sql = "update dlb set XH = '009' where ID = 1";
5.获取执行sql语句
Statement stat = null;
stat = conn.createStatement();
6.执行sql语句
int count = stat.executeUpdate(sql);
7.处理结果
System.out.println(count);
8.释放资源
stat.close();
conn.close();
以上是详细的步骤看起来有点抽象,下面我发一段整个代码看起来更直观一点
public class Demo01 {
public static void main(String[] args) throws Exception {
jdbc();
return;
}
private static void jdbc(){
Connection conn = null;
Statement stat = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?"
+ "useUnicode=true&characterEncoding=utf8&"
+ "useSSL=false&serverTimezone=Hongkong"
, "root", "123456");
//4.定义sql语句
String sql = "update dlb set XH = '009' where ID = 1";
//5.获取执行sql语句
stat = conn.createStatement();
//6.执行sql语句
int count = stat.executeUpdate(sql);
System.out.println(count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stat != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}