需要先下载mysql-connector-java-8.0.23.jar或者其他版本的jar包,如果有需要的小伙伴欢迎私信,博主私发。
下载好后把该文件复制到/Java0402/WebContent下的/Java0402/WebContent/WEB-INF中的lib文件下。
添加完成后会在Referenced_Libraries下有该jar包,如下图。
此时在保中建立一个类。
书写代码。
@Test
public void test2() {
// 通过数据库的链接执行CUD
// 得到数据库连接
Connection connection = getConnection();
if (connection != null) {
// 通过连接生成Statment对象
Statement statement = null;
try {
statement = connection.createStatement();
String sql = "INSERT INTO tb_user(USER_NAME,USER_AGE,USER_BIRTHDAY)VALUES('李四',21,'1990-10-15')";
// executeUpdate传输sql语句,返回的是受影响的行数
// statement声明;execute执行
int t = statement.executeUpdate(sql);
System.out.println("受影响的行数是" + t);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 自动垃圾回收机制不能回收数据库的连接和执行语句
// 先打开的后关闭
try {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
// 加载驱动(加载驱动一般需要写在静态代码块中,以保证这个驱动只加载一次)
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 自定义一个连接数据库的方法
private Connection getConnection() {
Connection connection = null;
try {
// 连接数据库的url,注意修改数据库的名称
// 两种方法(url无需记忆)
// String url =
// "jdbc:mysql://localhost:3306/java0402?useUnicode=true&characterEncoding=UTF-8";
String url = "jdbc:mysql://localhost:3306/java0402?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=true&allowMultiQueries=true";
String user = "root";
String password = "wang";
connection = DriverManager.getConnection(url, user, password);
System.out.println(connection.toString());
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}