1. 新建数据库
请自行安装mysql,安装教程这里不出示啦~~,mysql安装完成后按以下步调来新建数据、新建表
(1)打开 MySQLWorkbench
安装好mysql之后,找到安装位置打开 MySQLWorkbench
(2)新建数据库 test_db
(2)新建表 user
(3)给user表新增两条数据
2.新建maven项目
3.在maven配置文件pom.xml文件中添加mysql驱动器依赖配置并加载依赖
- <!--
- 继承Springboot的父项目
- 父级项目的作用:在父级项目中,规定好依赖的版本 子项目带入依赖的时候可以不写版本号,会依赖父级项目的版本
- -->
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.5.1</version>
- </parent>
- <dependencies>
- <!--
- 引入SpringBoot的web支持
- 如果 groupId 和 父级项目一样,说明都是SpringBoot的依赖
- 可以不写版本号 会依赖父级项目的版本
- spring-boot-starter-web 是web环境启动器
- -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!-- 添加MySQL驱动器的依赖 -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>8.0.21</version>
- </dependency>
- </dependencies>
复制代码 假如依赖下载失败,如下图
解决方案:
4. 新建包
输入包名,输入完成后回车
5. 在包下新建主类


MysqlConnectionDemo1文件的代码如下
- package com.fuyu;
- import java.sql.*;
- public class MysqlConnectionDemo1 {
- private static final String JDBC_Driver = "com.mysql.cj.jdbc.Driver";//jdbc驱动名称
- private static final String DB_Url = "jdbc:mysql://localhost:3306/test_db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";//数据库url
- private static final String DB_User = "root";//数据库的用户名
- private static final String DB_Password = "123456";//数据库的密码
- private static void MysqlConnection(){
- Connection connection = null;
- Statement statement = null;
- try{
- //1- 注册JDBC驱动
- Class.forName(JDBC_Driver);
- //2- 连接数据库
- System.out.println("开始连接数据库...");
- connection = DriverManager.getConnection(DB_Url,DB_User,DB_Password);
- //3- 执行查询
- System.out.println("开始实例化Stetement对象...");
- statement = connection.createStatement();
- String sql = "SELECT * FROM USER";//查询语句
- ResultSet rs = statement.executeQuery(sql);//执行查询语句
- //4- 展开结果集数据库
- while (rs.next()){
- int id = rs.getInt("id");
- String name = rs.getString("name");
- int age = rs.getInt("age");
- System.out.println("id===" + id);
- System.out.println("name===" + name);
- System.out.println("age===" + age);
- }
- //5- 关闭连接
- rs.close();
- statement.close();
- connection.close();
- }catch(SQLException se){
- se.printStackTrace();
- }catch (Exception e){
- e.printStackTrace();
- }finally {
- try{
- if(statement != null) statement.close();
- }catch (SQLException se2){
- }
- try{
- if(connection != null) connection.close();
- }catch (SQLException se3){
- se3.printStackTrace();
- }
- }
- }
- public static void main(String[] args){
- MysqlConnection();
- }
- }
复制代码 6. 运行项目
7. 运行效果-控制台打印如下图
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |