1.原生态连接
①:准备工作:引入mysql依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
②:书写DBUtil工具类:全代码
import java.sql.*;
public class DBUtil {
public static final String username="root";//连接数据库的用户名
public static final String password="***";//连接数据库的密码
public static final String url="jdbc:mysql://localhost:3306/db02?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8";//url的路径
public static Connection getCon() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return DriverManager.getConnection(url,username,password);
}
public static Statement getStatement(Connection connection) throws SQLException {
return connection.createStatement();
}
public static ResultSet getResultSet(Statement statement,String sql) throws SQLException {
return statement.executeQuery(sql);
}
}
③:连接数据库的四大步骤
1>:加载驱动
2>:获取连接
public static Connection getCon() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver"); //1.加载驱动
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return DriverManager.getConnection(url,username,password); //2.获取连接
}
3>:通过你的连接来获取操作数据库的statement对象
public static Statement getStatement(Connection connection) throws SQLException {
return connection.createStatement();//注:prepareStatement()可以防止SQL注入问题
}
4>:执行sql语句,获取结果集
public static ResultSet getResultSet(Statement statement,String sql) throws SQLException {
return statement.executeQuery(sql);
}
④:代码测试
1>:数据库表的设计:
1.原生态连接
①:准备工作:引入mysql依赖:
<dependency>