13.MySQL数据库JDBC编程

JDBC编程中主要用到的类/对象
1.DataSource 用于配置如何连接MySQL
2.Connection 表示建立好的一次连接(在操作数据库之前要先建立连接)
3.PrepareStatement 对应到一个SQL语句
4. ResultSet 表示select查找结果的结果集

1.先创建好MySQL的数据库

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| musicserver        |
| mysql              |
| performance_schema |
| sys                |
| test2              |
+--------------------+
13 rows in set (0.05 sec)

mysql> create database java_0224;
Query OK, 1 row affected (0.04 sec)

mysql> use java_0224;
Database changed

mysql> create table student(id int, name varchar(20), classId int);
Query OK, 0 rows affected (0.06 sec)

2.如果是增删改操作,整体的JDBC代码为:


import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TestJDBC01 {
    
    
    public static void main(String[] args) throws SQLException {
    
    
        //1.创建DataSource对象(dataSource生命周期是跟随整个程序)
        DataSource dataSource = new MysqlDataSource();
        //  接下来需要针对 DataSource进行一些配置,保证后面能够顺利的访问数据库
        //  主要配置三个信息:URL  User  Password
        //  以上过程需要进行向下转型
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java_0224?characterEncoding=utf-8&useSSL=true");
        //  此处的127.0.0.1就表示本机,只要Mysql装在本机都可以使用这个ip
        //  3306是端口号
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("09050797");

        //2.和数据库建立连接
        //  建立连接的意义是为了验证当前网络通信是否正常
        //  如果不正常就会抛出 SQLException异常
        //  connect生命周期是较短的,每个请求创建一个新的connect
        Connection connection = dataSource.getConnection();

        //3.拼装SQL语句,用到 PrepareStatement 对象
        //  当前示例中插入的数据内容是确定的。也可以动态拼接进去
//        String sql = "insert into student values(1, '曹操', 10)";
//        PreparedStatement statement = connection.prepareStatement(sql);
        //  动态拼装是这样的
        //  ?是一个占位符,可以把具体的变量的值替换到 ?位置
        int id = 1;
        String name = "曹操";
        int classId = 10;
        String sql = "insert into student values(?, ?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        //此处的1,2,3相当于 ? 的下标(从1开始算)
        statement.setInt(1,id);
        statement.setString(2,name);
        statement.setInt(3,classId);
        System.out.println("statement:"+statement);

        //4.拼装完之后,开始执行SQL
        //   insert  delete  update  都使用executeUpdate()方法
        //   select 使用 executeQuery() 来执行
        //返回值表示此次操作修改了多少行
        int ret = statement.executeUpdate();
        System.out.println("ret:" + ret);

        //5.执行完毕之后需要释放相关资源
        //  后创建的先释放
        statement.close();
        connection.close();
    }
}

运行结果为:

在这里插入图片描述

在数据库中查找发现已经添加成功了:
在这里插入图片描述

3.如果是查找操作,整体的JDBC代码为:

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//查找操作
public class TestJDBCSelect {
    
    
    public static void main(String[] args) throws SQLException {
    
    
        //1. 创建DataSource对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java_0224?characterEncoding=utf-8&useSSL=true");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("09050797");

        //2.创建Connection 对象
        Connection connection = dataSource.getConnection();

        //3.借助PrepareStatement拼装SQL语句
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);

        //4.执行SQL语句
        ResultSet resultSet = statement.executeQuery();

        //5.遍历结果集
        //  建立过程和使用迭代器遍历集合类有点像
        while (resultSet.next()){
    
    
            //resultSet 的光标指向了当前行,就可以把当前列中的数据全部获取到
            //当前表中的每一行包含三个列,id、name、classId,可以根据列名来获取对应列的数据
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            int classId = resultSet.getInt("classId");
            //此处参数中的列名必须和数据库中的列名完全一致,顺序无所谓
            System.out.println("id:"+id+"   name:"+name+"   classId:"+classId);
        }

        //6.关闭释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}

执行结果:
在这里插入图片描述

4.如果是删除操作,整体的JDBC代码为:


import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class TestJDBCDelect {
    
    
    public static void main(String[] args) throws SQLException {
    
    
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要删除的学生姓名");
        String name = scanner.next();
        //1.创建DataSource对象(dataSource生命周期是跟随整个程序)
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java_0224?characterEncoding=utf-8&useSSL=true");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("09050797");

        //2.和数据库建立连接
        Connection connection = dataSource.getConnection();

        //3.拼装SQL语句,用到 PrepareStatement 对象
        String sql = "delete from student where name = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,name);

        //4.拼装完之后,开始执行SQL
        int ret = statement.executeUpdate();
        if (ret == 1){
    
    
            System.out.println("删除成功");
        }else {
    
    
            System.out.println("删除失败");
        }

        //5.执行完毕之后需要释放相关资源
        statement.close();
        connection.close();
    }
}

执行结果为:
在这里插入图片描述
在数据库中查找得到:
在这里插入图片描述
删除成功!

5.如果是修改操作,整体的JDBC代码为:


import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class TestJDBCUpdata {
    
    
    public static void main(String[] args) throws SQLException {
    
    
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要修改的学生id");
        int id = scanner.nextInt();
        System.out.println("请输入要修改的学生name");
        String name = scanner.next();

        //1.创建DataSource对象(dataSource生命周期是跟随整个程序)
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java_0224?characterEncoding=utf-8&useSSL=true");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("09050797");

        //2.和数据库建立连接
        Connection connection = dataSource.getConnection();

        //3.拼装SQL语句,用到 PrepareStatement 对象
        String sql = "update student set name = ? where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,name);
        statement.setInt(2,id);

        //4.拼装完之后,开始执行SQL
        int ret = statement.executeUpdate();
        if (ret == 1){
    
    
            System.out.println("修改成功");
        }else {
    
    
            System.out.println("修改失败");
        }

        //5.执行完毕之后需要释放相关资源
        statement.close();
        connection.close();
    }
}

执行结果为:
在这里插入图片描述
数据库中执行结果:
在这里插入图片描述
修改成功!

猜你喜欢

转载自blog.csdn.net/qq_45136189/article/details/114032009
今日推荐