0
点赞
收藏
分享

微信扫一扫

JAVA的数据库编程-JDBC

infgrad 2022-01-21 阅读 98

配置好数据库连接后,接下来就需要在Java中来实现对数据库的操作了。

目录

一.JDBC编程的步骤

二.JDBC常用接口和类

1.数据库连接的2种方式

(1)通过DriverManager(驱动管理类)的静态方法获取

(2)通过DataSource(数据源)对象获取(实际中用的最多的方式)

(3)2种连接方式的区别 

3.发送sql语句到数据库中的三种方式

(1)Statement

(2)PreparedStatement(使用最多)

(3)CallableStatement

4.执行sql语句的的方法

(1)执行查找语句

(2)执行插入,修改,删除操作的语句

5.释放资源

三.增删改查操作的例子

1.插入操作

2.删除操作

3.修改操作

4.查询操作


一.JDBC编程的步骤

1. 创建数据库连接Connection
2. 创建操作命令Statement
3. 使用操作命令来执行SQL
4. 处理结果集ResultSet
5. 释放资源

二.JDBC常用接口和类

1.数据库连接的2种方式

(1)通过DriverManager(驱动管理类)的静态方法获取

        //加载JDBC驱动程序
        Class.forName("com.mysql.jdbc.Driver");
        //创建数据库连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&user=root&password=root&useSSL=false");

 

 这里的ip地址和端口号都是本机的,在自己使用的时候只需要修改数据库名和自己数据库的账号和自己设置的密码即可(一般数据库名默认为root)。

(2)通过DataSource(数据源)对象获取(实际中用的最多的方式)

        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/ebook?characterEncoding=utf-8");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("root");

(3)2种连接方式的区别 

DriverManager类每次使用完进行释放资源,关闭的是物理连接,不能重复利用;

而DataSource提供的是连接池,连接池在初始的时候会创建一些数据库连接,这些连接释放资源后都是将Connection对象进行回收,所以能够重复使用。

3.发送sql语句到数据库中的三种方式

(1)Statement

主要执行不带参数的简单sql语句。

(2)PreparedStatement(使用最多)

可以执行带参数或不带参数的sql语句,执行速度比第1种快,sql语句会预编译在数据库系统中。

使用这种方法书写sql语句可以使用占位符?(从1开始计数),比第1种方式安全

(3)CallableStatement

用于执行数据库存储过程的调用。

4.执行sql语句的的方法

(1)执行查找语句

executeQuery();

在执行查找的时候还需要使用ResultSet类对与查找结果集进行接收,最后使用该类中的next()方法通过循环来get到查询的内容

(2)执行插入,修改,删除操作的语句

executeUpdate();

这两个方法都在发送sql语句到数据库的类中。

5.释放资源

最后通过对应对象的close()方法进行资源释放。

三.增删改查操作的例子

注意:在增删改查中操作的前提是对应的数据库是正确的,且sql语句没有问题,才会执行成功,如果涉及到中文,还要保证字符编码为utf-8否则就会变成乱码。

下面的代码仅供参考,如果需要执行,则要修改里面的sql语句和自己的数据库。

1.插入操作

package sqljdbc.practice;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import com.sun.xml.internal.bind.v2.model.core.ID;

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

public class InsertData {
    public static void main(String[] args) throws SQLException {

        String stuName = "貂蝉";
        String bookName = "诗经";
        String startTime = "2019-09-25 17:50";
        String endTime = "2019-10-25 17:50";

        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/ebook?characterEncoding=utf-8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("root");

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            //进行数据库的连接
            connection =  dataSource.getConnection();

            //查询名字对应的id
            String sql1 = "select id from student where name = ?";
            statement =  connection.prepareStatement(sql1);
            statement.setString(1,stuName);
            resultSet= statement.executeQuery();
            int stu_id = 0;
            while (resultSet.next()){
                stu_id = resultSet.getInt("id");
            }
            System.out.println("学生id: "+stu_id);
            //查询书名对应的id
            String sql2 = "select id from book where name = ?";
            statement = connection.prepareStatement(sql2);
            statement.setString(1,bookName);
            resultSet = statement.executeQuery();
            int book_id = 0;
            while (resultSet.next()){
                book_id = resultSet.getInt("id");
            }
            System.out.println("书id: "+book_id);
               //这里通过占位符来动态地设置需要插入的内容
            String sql = "insert into borrow_info (book_id,student_id,start_time,end_time)" +
                    " values(?,?,?,?)";
            statement =  connection.prepareStatement(sql);
            //动态指定占位符中的内容
            statement.setInt(1,book_id);
            statement.setInt(2,stu_id);
            statement.setString(3,startTime);
            statement.setString(4,endTime);
            int res = statement.executeUpdate();

        } finally {
            //避免数据库连接失败,导致对象为空
            if (resultSet != null){
                resultSet.close();
            }
            if(statement != null){
                statement.close();
            }
            if(connection != null){
                connection.close();
            }
        }


    }
}


2.删除操作

package sqljdbc.practice;

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 DeleteData {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/ebook?characterEncoding=utf-8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("root");

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = dataSource.getConnection();

            String sql = "delete from borrow_info where id = (select max(id) from borrow_info)";
            preparedStatement = connection.prepareStatement(sql);
            int res = preparedStatement.executeUpdate();
            System.out.println(res);
        } finally {
            if(preparedStatement != null){
                preparedStatement.close();
            }
            if(connection != null){
                connection.close();
            }

        }
    }
}

3.修改操作

package sqljdbc.practice;

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 UpdateData {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource= new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/ebook?characterEncoding=utf-8&useSSl=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("root");

        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = dataSource.getConnection();

            String sql = "update book  set price = 61.20 where name = '深入理解Java虚拟机'";
            preparedStatement = connection.prepareStatement(sql);

            int res = preparedStatement.executeUpdate();//修改
        } finally {
            if(preparedStatement != null){
                preparedStatement.close();
            }
            if(connection != null){
                connection.close();
            }
        }


    }
}

4.查询操作

package sqljdbc.practice;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import com.sun.xml.internal.bind.v2.model.core.ID;

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

public class InsertData {
    public static void main(String[] args) throws SQLException {

        String stuName = "貂蝉";
        String bookName = "诗经";
        String startTime = "2019-09-25 17:50";
        String endTime = "2019-10-25 17:50";

        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/ebook?characterEncoding=utf-8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("root");

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection =  dataSource.getConnection();

            //查询名字对应的id
            String sql1 = "select id from student where name = ?";
            statement =  connection.prepareStatement(sql1);
            statement.setString(1,stuName);
            resultSet= statement.executeQuery();
            int stu_id = 0;
            while (resultSet.next()){
                stu_id = resultSet.getInt("id");
            }
            System.out.println("学生id: "+stu_id);
            //查询书名对应的id
            String sql2 = "select id from book where name = ?";
            statement = connection.prepareStatement(sql2);
            statement.setString(1,bookName);
            resultSet = statement.executeQuery();
            int book_id = 0;
            while (resultSet.next()){
                book_id = resultSet.getInt("id");
            }
            System.out.println("书id: "+book_id);

            String sql = "insert into borrow_info (book_id,student_id,start_time,end_time)" +
                    " values(?,?,?,?)";
            statement =  connection.prepareStatement(sql);
            statement.setInt(1,book_id);
            statement.setInt(2,stu_id);
            statement.setString(3,startTime);
            statement.setString(4,endTime);
            int res = statement.executeUpdate();

        } finally {
            if (resultSet != null){
                resultSet.close();
            }
            if(statement != null){
                statement.close();
            }
            if(connection != null){
                connection.close();
            }
        }


    }
}

举报

相关推荐

0 条评论