1、在src下创建一个db.properties文件,里面存放驱动信息driver、url、username、password
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai username=root password=123456
2、创建一个utils包,在其下创建一个JdbcUtils类,具备驱动数据库、获取数据连接、释放连接资源的功能
package com.utils;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
//静态驱动
static {
try{
//从db.properties文件中提取驱动信息
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);//将驱动信息装载到properties对象中
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//1、驱动只用加载一次
Class.forName(driver);
}catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
//释放连接资源
public static void release(Connection cn, Statement st, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(cn!=null){
try {
cn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
3、具体执行SQL语句的实现,在执行SQL语句时使用PreparedStatement执行,防止SQL注入
package com.jdbc;
import com.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
public class Demo3 {
public static void main(String[] args) {
Connection cn = null;
PreparedStatement ps = null;
try {
String sql = "insert into users(id,name,password,email,birthday) values(?,?,?,?,?);";
cn = JdbcUtils.getConnection();//获取数据库连接
ps = cn.prepareStatement(sql);//使用PreparedStatement代替Statement,防止SQL注入,SQL语句中传入的参数用?占位
//按?位置顺序设置传递的参数
ps.setInt(1,4);
ps.setString(2,"demo2");
ps.setString(3,"123456");
ps.setString(4,"demo2@qq.com");
// java.util.Date为Java提供的jar包,先用new Date().getTime()获取本地时间戳
// java.sql.Date为数据库提供的jar包,再用sql提供的方法转换成sql可以识别的类型
ps.setDate(5,new java.sql.Date(new Date().getTime()));
int i = ps.executeUpdate();
if( i>0) {
System.out.println("插入成功!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(cn,ps,null);
}
}
}