1.原生态连接 ①:准备工作:引入Mysql依赖: mysql mysql-connector-java 5.1.6 ②:书写DBUtil工具
mysql mysql-connector-java 5.1.6
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); }}
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.获取连接 }
public static Statement getStatement(Connection connection) throws SQLException { return connection.createStatement();//注:prepareStatement()可以防止SQL注入问题 }
public static ResultSet getResultSet(Statement statement,String sql) throws SQLException { return statement.executeQuery(sql); }
user表:
@springBootTestclass 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("==============="); } } }}
以yml文件为例:
spring: datasource: url: jdbc:mysql://localhost:3306/db02?ServerTimezone=UTC username: root password: *** driver-class-name: com.mysql.cj.jdbc.Driver
以上就是关于自己总结的连接mysql数据库的两种方法,实际的操作也不难,希望可以帮助到大家!
来源地址:https://blog.csdn.net/qq_51933234/article/details/129669918
--结束END--
本文标题: Mysql的数据库连接---SpringBoot
本文链接: https://www.lsjlt.com/news/392601.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-12
2024-05-12
2024-05-12
2024-05-12
2024-05-12
2024-05-12
2024-05-12
2024-05-11
2024-05-11
2024-05-11
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0