JDBC系列一之--------使用JDBC连接Mysql数据库进行增删改查操作(详细版)

最近发现了一个挺厉害的人工智能学习网站,内容通俗易懂,风趣幽默,感兴趣的可以点击此链接进行查看:床长人工智能教程

 废话不多说,请看正文!

目录

一、连接数据库

1.我的java和mysql版本

2.连接数据库的版本一

3.连接数据库的版本二

4.连接数据库的版本三

5.连接数据库的版本四

6.连接数据库的版本五

7.连接数据库的最终版本(将连接数据库和关闭数据库封装成一个类,减少重复代码) 

二、对Mysql 数据库进行增删改操作

1.我的数据库 customers 表的内容

2.对数据库中进行插入数据(没有使用连接数据库的封装库,区别请对比2和3)

3.对数据库进行修改操作(请与第2点进行对比一下连接数据库和关闭数据库的差别)

4.对数据库通用的增删改操作(终极版)

三、对数据库进行查询操作

1.建立一个Customer 类

2.对customers表的查询实例

3.对customers表通用的查询操作(进阶版)

4.针对于不同的表的通用的查询操作,返回表中的一条记录

5.针对于不同的表的通用的查询操作,返回表中的多条记录

JDBC系列

JDBC系列一之------使用JDBC连接Mysql数据库进行增删改查操作(详细版)

JDBC系列二之------Jdbc操作Mysql BLOB类型数据

JDBC系列三之------java下Mysql的批量插入的优化

JDBC系列四之------JDBC对mysql数据库事务处理

JDBC系列五之------java的Dao及其实现类

JDBC系列六之------JDBC数据库连接池


一、连接数据库

1.我的java和mysql版本

javaMysql
1.88.0

2.连接数据库的版本一

//方法一
    @Test
    public void testConnection1() throws SQLException{
        //1.获取Driver 类对象
        Driver driver = new com.mysql.cj.jdbc.Driver();

        String url = "jdbc:mysql://localhost:3306/test?" +
                "useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        // 将用户名和密码封装在Properties中
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "root");

        Connection conn = driver.connect(url, info);

        System.out.println(conn);
    }

3.连接数据库的版本二

//方法二:对方式一进行迭代,使得如下程序不出现第三方API,让程序有更好的可移植性
    @Test
    public void  testConnection2() throws Exception{
        //1. 获取Driver类对象,使用反射
        Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) clazz.newInstance();

        //2. 提供要连接的数据库
        String url = "jdbc:mysql://localhost:3306/test?" +
                "useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        //3. 将用户名和密码封装在Properties中
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "root");
        //4.获取连接
        Connection conn = driver.connect(url, info);
        System.out.println(conn);

    }

4.连接数据库的版本三

//方法三:使用DriverManger替换Driver
    @Test
    public void testConnection3() throws  Exception{
        //1. 获取Driver类对象,使用反射
        Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) clazz.newInstance();

        //2.提供另外的三个基本信息
        String url = "jdbc:mysql://localhost:3306/test" +
                "?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        String user = "root";
        String password = "root";

        //注册驱动
        DriverManager.registerDriver(driver);
        //获取连接
        Connection conn= DriverManager.getConnection(url, user, password);
        System.out.println(conn);
    }

5.连接数据库的版本四

//方法四:
    @Test
    public void testConnection4() throws  Exception{
        //1.提供三个基本信息
        String url = "jdbc:mysql://localhost:3306/test" +
                "?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        String user = "root";
        String password = "root";

        //2. 获取Driver类对象,使用反射
        Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
        //相较于方式三,可以省略以下代码
//        Driver driver = (Driver) clazz.newInstance();
//        //注册驱动
//        DriverManager.registerDriver(driver);


        //3.获取连接
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);
    }

6.连接数据库的版本五

 jdbc.properties 文件内容

user=root
password=659647
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driverClass=com.mysql.cj.jdbc.Driver
//方式五:将数据库连接的基本数据声明在配置文件中,通过读取配置文件的信息,获取连接
    /*
    * 这种的好处
    * 1.实现数据与代码的分离,实现了解耦。
    * 2.如果需要修改配置文件信息,可以避免程序重新打包
    * */
    @Test
    public void testConnection5() throws Exception{
        //1.读取配置文件的基本信息
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        pros.load(is);

        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        String driverClass = pros.getProperty("driverClass");

        //2.加载驱动
        Class.forName(driverClass);

        //3.获取连接
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);
    }

7.连接数据库的最终版本(将连接数据库和关闭数据库封装成一个类,减少重复代码) 

jdbc.properties 文件内容

user=root
password=659647
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driverClass=com.mysql.cj.jdbc.Driver
/**
 * 操作数据库的工具类
 */

public class JDBCUtils {

    /*
    *  获取数据库的连接
    * */
    public static Connection getConnection() throws Exception{
        //1.读取配置文件的基本信息
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        pros.load(is);

        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        String driverClass = pros.getProperty("driverClass");

        //2.加载驱动
        Class.forName(driverClass);

        //3.获取连接
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }


    /*
    *  关闭连接和Statement的操作
    * */
    public static void closeResource(Connection conn, Statement ps){
        try {
            if( ps != null)
                ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /*
    * 关闭资源的操作
    * */
    public static void closeResource(Connection conn, Statement ps , ResultSet rs){
        try {
            if( ps != null)
                ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

二、对Mysql 数据库进行增删改操作

1.我的数据库 customers 表的内容

2.对数据库中进行插入数据(没有使用连接数据库的封装库,区别请对比2和3)

//向customers表中添加一条数据
    @Test
    public void  testInsert() {
        Connection connection = null;
        PreparedStatement ps =  null;
        try {
            //1.读取配置文件的基本信息
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
            Properties pros = new Properties();
            pros.load(is);

            String user = pros.getProperty("user");
            String password = pros.getProperty("password");
            String url = pros.getProperty("url");
            String driverClass = pros.getProperty("driverClass");

            //2.加载驱动
            Class.forName(driverClass);

            //3.获取连接
            connection = DriverManager.getConnection(url, user, password);

            //4.预编译sql语句,返回PreparedStatement的实例
            String sql = "insert into customers(name,email,birth)value(?,?,?)";
            ps = connection.prepareStatement(sql);
            //5.填充占位符
            ps.setString(1,"哪吒");
            ps.setString(2,"nezha@gmail.com");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse("1000-01-01");
            ps.setDate(3,new java.sql.Date(date.getTime()));

            //6.执行sql
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //7.资源关闭
            try {
                if( ps != null)
                    ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if(connection != null)
                    connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }

3.对数据库进行修改操作(请与第2点进行对比一下连接数据库和关闭数据库的差别)

//修改customers表中的数据
    @Test
    public void testUpdate(){
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            //1.获取数据库连接
            conn = JDBCUtils.getConnection();
            //2.预编译sql语句,返回PreparedStatement的实列
            String sql = "update customers set name = ? where id = ?";
            ps = conn.prepareStatement(sql);
            //3.填充占位符
            ps.setObject(1,"莫扎特");
            ps.setObject(2,18);
            //4.执行
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //5.资源的关闭
            JDBCUtils.closeResource(conn,ps);
        }
    }

4.对数据库通用的增删改操作(终极版)

//通用的增删改操作
    public void update(String sql, Object ...args){//sql语句的占位符数量和可变形参的数量相同
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            //1.获取数据库连接
            conn = JDBCUtils.getConnection();
            //2.预编译sql语句,返回PreparedStatement的实列
            ps = conn.prepareStatement(sql);
            //3.填充占位符
            for (int i=0;i<args.length;i++){
                ps.setObject(i + 1, args[i]);
            }
            //4.执行
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //5.资源的关闭
            JDBCUtils.closeResource(conn,ps);
        }

    }

对上述的代码进行测试

@Test
    public void testCommonUpdate(){
//        String sql = "delete from customers where id = ?";
//        update(sql,4);
        //order 是sql中的关键字,当order作为一个表名时要添加符合: `
        String sql = "update `order` set order_name = ? where order_id = ?";
        update(sql,"DD",2);
    }

三、对数据库进行查询操作

1.建立一个Customer 类

/*
* ORM编程思想 (object relational mapping)
* 一个数据表对应一个java类
* 表中的每一条记录对应java类的一个对象
* 表中的一个字段对应java类的一个属性
* */

public class Customer {
    private int id;
    private String name;
    private String email;

    public Customer() {
        super();
    }

    public Customer(int id, String name, String email, Date birth) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.birth = birth;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    private Date birth;
    
}

2.对customers表的查询实例

@Test
    public void testQuery1(){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            //获取连接
            conn = JDBCUtils.getConnection();
            String sql = "select id, name,email,birth from customers where id = ?";
            //预编译sql语句
            ps = conn.prepareStatement(sql);
            //填充占位符
            ps.setObject(1,1);

            //执行并返回结果集
            resultSet = ps.executeQuery();
            //处理结果集
            if (resultSet.next()){//判断结果集下一条是否有数据如果有数据放回true,并自动指向下一条数据,
                                  // 没有数据返回false.
                //获取当前数据的各个字段值
                int id = resultSet.getInt(1);
                String name =  resultSet.getString(2);
                String email = resultSet.getString(3);
                Date birth = resultSet.getDate(4);

                //输出方式:
//                Object[] data = new Object[]{id,name,email,birth};
                //输出方式:将数据封装成要给对象(推荐)
                Customer customer = new Customer(id, name, email, birth);
                System.out.println(customer);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            JDBCUtils.closeResource(conn,ps,resultSet);
        }

    }

3.对customers表通用的查询操作(进阶版)

/*
    * 针对于customers表通用的查询操作
    * */
    public Customer queryForCustomers(String sql, Object ...args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = JDBCUtils.getConnection();
            //预编译sql语句
            ps = conn.prepareStatement(sql);
            //填充占位符
            for (int i = 0; i < args.length; i++){
                ps.setObject(i + 1,args[i]);
            }
            //执行并返回结果集
            rs = ps.executeQuery();
            //获取结果集元素据
            ResultSetMetaData rsmd = rs.getMetaData();
            //通过ResultSetMetaData获取数据集中的列数
            int columnCount = rsmd.getColumnCount();

            if (rs.next()){
                Customer cust = new Customer();
                for (int i = 0;i < columnCount; i++){
                    Object columnValue = rs.getObject(i + 1);
                    //获取每个列的列名:getColumnName(不推荐使用)
                    //获取每个列的别名:getColumnLabel
                    //String columnName = rsmd.getColumnName(i + 1);
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    //给cust 对象指定的columnName属性赋值为columnValue,通过反射
                    Field field = Customer.class.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(cust,columnValue);
                }
                return cust;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.closeResource(conn,ps,rs);
        }
        return null;
    }

对上面代码的测试类

    @Test
    public void testQueryForCustomers(){
        String sql = "select id, name,email,birth from customers where id = ?";
        Customer customer = queryForCustomers(sql, 13);
        System.out.println(customer);

        String sql1 = "select id, name,email,birth from customers where name = ?";
        Customer customer1 = queryForCustomers(sql1, "成龙");
        System.out.println(customer1);
    }

4.针对于不同的表的通用的查询操作,返回表中的一条记录

/**
     *
     * 针对于不同的表的通用的查询操作,返回表中的一条记录
     */
    public <T> T getInstance(Class<T> clazz,String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();

            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            rs = ps.executeQuery();
            // 获取结果集的元数据 :ResultSetMetaData
            ResultSetMetaData rsmd = rs.getMetaData();
            // 通过ResultSetMetaData获取结果集中的列数
            int columnCount = rsmd.getColumnCount();

            if (rs.next()) {
                T t = clazz.newInstance();
                // 处理结果集一行数据中的每一个列
                for (int i = 0; i < columnCount; i++) {
                    // 获取列值
                    Object columValue = rs.getObject(i + 1);

                    // 获取每个列的列名
                    // String columnName = rsmd.getColumnName(i + 1);
                    String columnLabel = rsmd.getColumnLabel(i + 1);

                    // 给t对象指定的columnName属性,赋值为columValue:通过反射
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columValue);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps, rs);

        }

        return null;
    }

对上面代码的测试类

 @Test
    public void testGetInstance(){
        String sql = "select id,name,email from customers where id = ?";
        Customer customer = getInstance(Customer.class,sql,12);
        System.out.println(customer);

//        String sql1 = "select order_id orderId,order_name orderName from `order` where order_id = ?";
//        Order order = getInstance(Order.class, sql1, 1);
//        System.out.println(order);
    }

5.针对于不同的表的通用的查询操作,返回表中的多条记录

public <T> List<T> getForList(Class<T> clazz, String sql, Object... args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();

            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            rs = ps.executeQuery();
            // 获取结果集的元数据 :ResultSetMetaData
            ResultSetMetaData rsmd = rs.getMetaData();
            // 通过ResultSetMetaData获取结果集中的列数
            int columnCount = rsmd.getColumnCount();
            //创建集合对象
            ArrayList<T> list = new ArrayList<T>();
            while (rs.next()) {
                T t = clazz.newInstance();
                // 处理结果集一行数据中的每一个列:给t对象指定的属性赋值
                for (int i = 0; i < columnCount; i++) {
                    // 获取列值
                    Object columValue = rs.getObject(i + 1);

                    // 获取每个列的列名
                    // String columnName = rsmd.getColumnName(i + 1);
                    String columnLabel = rsmd.getColumnLabel(i + 1);

                    // 给t对象指定的columnName属性,赋值为columValue:通过反射
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columValue);
                }
                list.add(t);
            }

            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps, rs);

        }

        return null;
    }

对上面代码的测试类

/**
     *
     * 针对于不同的表的通用的查询操作,返回表中的多条记录
     */
    @Test
    public void testGetForList(){

        String sql = "select id,name,email from customers where id < ?";
        List<Customer> list = getForList(Customer.class,sql,12);
        list.forEach(System.out::println);

        String sql1 = "select order_id orderId,order_name orderName from `order`";
        List<Order> orderList = getForList(Order.class, sql1);
        orderList.forEach(System.out::println);
    }

JDBC系列

  • 2
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以通过 JDBC 连接 MySQL 数据库,并实现增删改查操作。以下是一个简单的示例代码: ```java import java.sql.*; public class JdbcExample { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/test"; static final String USER = "root"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // 注册 JDBC 驱动器 Class.forName(JDBC_DRIVER); // 打开连接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); // 执行查询 System.out.println("创建查询..."); stmt = conn.createStatement(); String sql = "SELECT id, name, age FROM student"; ResultSet rs = stmt.executeQuery(sql); // 处理结果集 while (rs.next()) { // 获取数据 int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); // 显示数据 System.out.print("ID: " + id); System.out.print(", Name: " + name); System.out.println(", Age: " + age); } // 关闭连接 rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { // 处理 JDBC 错误 se.printStackTrace(); } catch (Exception e) { // 处理 Class.forName 错误 e.printStackTrace(); } finally { // 关闭资源 try { if (stmt != null) { stmt.close(); } } catch (SQLException se) { } try { if (conn != null) { conn.close(); } } catch (SQLException se) { se.printStackTrace(); } } } } ``` 上述代码实现了查询操作,如果要实现增删改操作可以使用 PreparedStatement 来执行 SQL 语句。例如,插入数据的示例代码如下: ```java // 创建 PreparedStatement 对象 String sql = "INSERT INTO student (name, age) VALUES (?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); // 设置参数 pstmt.setString(1, "Tom"); pstmt.setInt(2, 20); // 执行更新 int rows = pstmt.executeUpdate(); // 关闭资源 pstmt.close(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zpeien

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值