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>:数据库表的设计:
user表:
2>:在SpringBoot的测试单元经行测试
@SpringBootTest
class MysqlApplicationTests {
@Test
void contextLoads() throws SQLException {
Connection connection = DBUtil.getCon();//驱动加载和连接
Statement statement = DBUtil.getStatement(connection);//得到statement对象
ResultSet resultSet = DBUtil.getResultSet(statement, "select * from db02.user");//执行CRUD的sql语句得到结果集
if(resultSet!=null){
while (resultSet.next()){//遍历结果集,打印查询结果
String id = resultSet.getString(1);
String username=resultSet.getString(2);
String password=resultSet.getString(3);
String email = resultSet.getString(4);
String sex = resultSet.getString(5);
String age = resultSet.getString(6);
System.out.println(id+" "+username+" "+password+" "+email+" "+sex+" "+age);
System.out.println("===============");
}
}
}
}
3>:测试结果
2.在yml或则properties文件里,直接配置
以yml文件为例:
spring:
datasource:
url: jdbc:mysql://localhost:3306/db02?ServerTimezone=UTC
username: root
password: ***
driver-class-name: com.mysql.cj.jdbc.Driver
3.总结
以上就是关于自己总结的连接mysql数据库的两种方法,实际的操作也不难,希望可以帮助到大家!