1.装载Mysql驱动
给项目配置jar包:mysql-connector-java-8.0.19.jar(我选择的)
利用反射:Class.forName("com.mysql.jdbc.Driver");
Class.forName() 方法要求JVM查找并加载指定的类到内存中,由于JVM 加载类文件时会执行其中的静态代码块,从Driver类的源码中可以看到该静态代码块执行的操作是:将mysql的driver注册到系统的DriverManager中。
2.利用Connection接口连接
public static void main(String[] args) {
//加载驱动类
try {
Class.forName("com.mysql.cj.jdbc.Driver");
long start=System.currentTimeMillis();
String url="jdbc:mysql://localhost:3306/testjdbc?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";//0x版本数据库驱动文件的url基本格式: 连接地址+ssl连接关闭+字符集为utf-8+时区设置,testjdbc是数据库名
Connection conn=DriverManager.getConnection(url,"root","xjh1999");//建立连接
System.out.println(conn);
long end=System.currentTimeMillis();
System.out.println("建立连接耗时"+(end-start)+"ms毫秒");//开发中为提高效率,使用连接池
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
3.利用Statement接口执行静态SQL语句
注意:
正常情况不选用,因为会发生SQL注入,当传入参数时传入恶意代码,导致数据库不安全。
Statement stmt=conn.createStatement();
//定义一个接口语句
String sql01="INSERT INTO user_test(id,username,salary) VALUES (5,'四毛',600000)";
stmt.execute(sql01);
3.利用PreparedStatement接口执行静态SQL语句
//定义一个接口语句
String sql01="INSERT INTO user_test(username,salary) VALUES (?,?)";//?为占位服
PreparedStatement ps=conn.prepareStatement(sql01);
ps.setObject(1,"四毛2");//对数据预处理,防止SQL注入,1为上面?的参数索引,从1开始
ps.setObject(2,"150000");
ps.execute();
3.利用PreparedStatement接口的executeQuery()执行select语句得到结果集
public class Demo02 {
public static void main(String[] args) {
Connection conn= null;
PreparedStatement ps = null;
ResultSet rs=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/testjdbc?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
conn= DriverManager.getConnection(url,"root","xjh1999");//建立连接
//定义一个接口语句
String sql01="select username,salary from user_test where id>?";//?为占位服
ps=conn.prepareStatement(sql01);
ps.setObject(1,"2");//?为2,即id>2
rs= ps.executeQuery();
while(rs.next()){//往前移动游标
System.out.println(rs.getString(1)+"-----"+rs.getBigDecimal(2));//1代表每行的第一列数据,2代表第二列数据
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
4.在finally语句内,遵循:resultset->statement->connection的关闭顺序,并将三个try catch分开写
finally {
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}