JDBC的使用(5个步骤)

1,建立数据库连接Connection

在这里,创建数据库的连接有两种方法
1,通过DriverManager的静态方法获取

Class.forName("com.mysql.jdbc.Driver"); //加载JDBC驱动程序           
      Connection connection = DriverManager.getConnection(URL,USER_NAME,PASSWORD);

对于这种方法, DriverManager类来获取的Connection连接,是无法重复利用的,每次使用完以后释放资源时,通过connection.close()都是关闭物理连接。所以效率比较低.
2,通过DataSource(数据源获取对象).一般在实际应用中会使用这种方法.

DataSource dataSource = new MysqlDataSource();
dataSource.setUrl(URL);
dataSource.setUser(USER_NAME);
dataSource.setPassword(PASSWORD);
Connection connection = dataSource.getConnection();

对于这种来说, DataSource提供连接池的支持。连接池在初始化时将创建一定数量的数据库连接,这些连接是可以复用的,每次使用完数据库连接,释放资源调用connection.close()都是将Conncetion连接对象回收。

2,创建操作命令Statement

3, 使用操作命令来执行SQL

Statement对象主要是将SQL语句发送到数据库中。JDBC API中主要提供了三种Statement对象.
1,Statment,用于执行不带参数的简单sql语句.

Statement statement = connection.createStatement();
ResultSet resultSet= statement.executeQuery("select * from book"); //以select * from book举例

2,preparedStatement,
(1)用于执行带参或者不带参的sql语句.
(2)SQL语句会与预编译在数据库系统
(3)执行速度快于Statment

PreparedStatement preparedStatement = connection.prepareStatement("select * from book");
ResultSet resultSet = preparedStatement.executeQuery();//executeQuery() 方法执行后返回单个结果集的,通常用于select语句
//executeUpdate()方法返回值是一个整数,指示受影响的行数,通常用于update、insert、delete语句

3,CallableStatment,用于执行数据库存储过程中的调用

4. 处理结果集ResultSet

ResultSet对象它被称为结果集,它代表符合SQL语句条件的所有行,并且它通过一套getXXX方法提供了对这些行中数据的访问。
ResultSet里的数据一行一行排列,每行有多个字段,并且有一个记录指针,指针所指的数据行叫做当 前数据行,我们只能来操作当前的数据行。我们如果想要取得某一条记录,就要使用ResultSet的next()方法,如果我们想要得到ResultSet里的所有记录,就应该使用while循环。

while (resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String author = resultSet.getString("author");
                Double price = resultSet.getDouble("price");
                System.out.println(String.format("id=%d,name=%s,author=%s,price=%.2f",id,name,author,price));
            }

5. 释放资源

try {
            if(resultSet!=null){
                resultSet.close();
            }
            if (preparedStatement!=null){
                preparedStatement.close();
            }
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException e) {
           throw new RuntimeException("数据库释放资源错误!");
        }

下面是两种方式的举例完整代码
1,通过DriverManager

import java.sql.*;
public class DBUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/ebook";
    //MySQL数据连接的URL参数格式如下:
//jdbc:mysql://服务器地址:端口/数据库名?参数名=参数值
    private static final String USER_NAME = "root";
    private static final String PASSWORD ="123456";
    public static void main(String args[]) {
        Connection connection=null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");                //加载JDBC驱动程序:反射,这样调用初始化com.mysql.jdbc.Driver类,即将该类加载到JVM方法区,并执行该类的静态方法块、静态属性。
            connection = DriverManager.getConnection(URL,USER_NAME,PASSWORD); //1.创建数据库连接,创建连接对象
            System.out.println(connection);
            statement = connection.createStatement();        //2.创建操作命令statement
            resultSet= statement.executeQuery("select * from book");  //3.使用操作命令来执行SQL
            /*4. 处理结果集ResultSet*/
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String author = resultSet.getString("author");
                Double price = resultSet.getDouble("price");
                System.out.println(String.format("id=%d,name=%s,author=%s,price=%.2f",id,name,author,price));
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
        /*5.释放资源*/
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2,通过DataSource

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.*;
public class DBUtil1 {
    private static final String URL = "jdbc:mysql://localhost:3306/ebook";
    private static final String USER_NAME = "root";
    private static final String PASSWORD ="123456";
    private static MysqlDataSource DATASOURCE = new MysqlDataSource();
    static {
        DATASOURCE.setUrl(URL);
        DATASOURCE.setUser(USER_NAME);
        DATASOURCE.setPassword(PASSWORD);
    }
    public static Connection getConnection(){
        try {
            return DATASOURCE.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("获取数据库连接失败!");
        }
    }
    public static void close(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
        try {
            if(resultSet!=null){
                resultSet.close();
            }
            if (preparedStatement!=null){
                preparedStatement.close();
            }
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException e) {
           throw new RuntimeException("数据库释放资源错误!");
        }
    }
}
import java.sql.*;
public class Select { //这里只完成了查找操作,其他的可以自己补上
    public static void main(String args[]){
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Connection connection = DBUtil1.getConnection();
        String sql = "select * from book";
        try {
            preparedStatement = connection.prepareStatement(sql);
            //preparedStatement.setString();
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                Integer id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String author = resultSet.getString("author");
                Double price = resultSet.getDouble("price");
                System.out.println(String.format("id=%d,name=%s,author=%s,price=%.2f",id,name,author,price));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil1.close(connection,preparedStatement,resultSet );
        }
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值