如何使用JDBC连接数据库并执行SQL语句

2023-05-18 08:05:13 语句 如何使用 连接数据库

1. JDBC入门

JDBC(Java Database Connectivity)是Java程序与数据库进行交互的一种标准接口,它提供了一种简单的方式来连接和操作数据库。在使用JDBC之前,需要先了解以下几个概念:

  • JDBC Driver:JDBC驱动程序是一个Java类,用于将Java应用程序与特定数据库管理系统(DBMS)连接。JDBC驱动程序分为四种类型:JDBC-ODBC桥接驱动程序、本地api驱动程序、网络协议驱动程序和本地协议驱动程序。
  • Connection:Connection是一个JDBC接口,用于连接到数据库。在Java程序中,通过Connection接口的实现类来实现与数据库的连接。
  • Statement:Statement是一个JDBC接口,用于向数据库发送sql语句并执行它们。在Java程序中,通过Connection对象创建Statement对象。
  • ResultSet:ResultSet是一个JDBC接口,用于表示从数据库中检索到的结果集。ResultSet对象通过Statement对象的executeQuery()方法返回。

下面是一个简单的JDBC连接示例:

import java.sql.*;
public class JDBCDemo {
    public static void main(String[] args) {
        try {
            // 加载JDBC驱动程序
            Class.forName("com.Mysql.cj.jdbc.Driver");
            // 建立数据库连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "passWord");
            // 执行SQL查询
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM users");
            while (rs.next()) {
                System.out.println(rs.getInt(1) + ", " + rs.getString(2) + ", " + rs.getString(3));
            }
            // 关闭数据库连接
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. 抽取工具类

在实际开发中,我们通常会抽取出一个JDBC工具类来封装JDBC相关操作,以方便代码的重用和维护。下面是一个简单的JDBC工具类示例:

import java.sql.*;
public class JDBCUtils {
    private static final String URL = "jdbc:mysql://localhost:3306/mydb";
    private static final String USER = "root";
    private static final String PASSWORD = "password";
    static {
        try {
            // 加载JDBC驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        Connection conn = null;
        try {
            // 建立数据库连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void release(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

3. Statement CRUD

Statement是JDBC中最基本的操作方式,它用于向数据库发送SQL语句并执行它们。下面是一个使用Statement进行CRUD操作的示例:

import java.sql.*;
public class StatementCRUD {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            stmt = conn.createStatement();
            // 插入数据
            String sql = "INSERT INTO users (name, age) VALUES ('Tom', 18)";
            stmt.executeUpdate(sql);
            // 更新数据
            sql = "UPDATE users SET age = 20 WHERE name = 'Tom'";
            stmt.executeUpdate(sql);
            // 删除数据
            sql = "DELETE FROM users WHERE age = 20";
            stmt.executeUpdate(sql);
            // 查询数据
            sql = "SELECT * FROM users";
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                System.out.println(rs.getInt(1) + ", " + rs.getString(2) + ", " + rs.getInt(3));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(rs, stmt, conn);
        }
    }
}

4. 演练CRUD

下面是一个使用PreparedStatement进行CRUD操作的示例:

import java.sql.*;
public class PreparedStatementCRUD {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            // 插入数据
            String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "Tom");
            pstmt.setInt(2, 18);
            pstmt.executeUpdate();
            // 更新数据
            sql = "UPDATE users SET age = ? WHERE name = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, 20);
            pstmt.setString(2, "Tom");
            pstmt.executeUpdate();
            // 删除数据
            sql = "DELETE FROM users WHERE age = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, 20);
            pstmt.executeUpdate();
            // 查询数据
            sql = "SELECT * FROM users";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getInt(1) + ", " + rs.getString(2) + ", " + rs.getInt(3));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(rs, pstmt, conn);
        }
    }
}

5. Dao模式(声明与实现分开)

Dao(Data Access Object)模式是一种用于封装数据访问逻辑的设计模式。它将数据访问逻辑与业务逻辑分离开来,使得代码更易于维护和扩展。下面是一个使用Dao模式进行CRUD操作的示例:

import java.sql.*;
public class UserDAO {
    private static final String INSERT_SQL = "INSERT INTO users (name, age) VALUES (?, ?)";
    private static final String UPDATE_SQL = "UPDATE users SET age = ? WHERE name = ?";
    private static final String DELETE_SQL = "DELETE FROM users WHERE age = ?";
    private static final String SELECT_SQL = "SELECT * FROM users";
    public void insert(User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(INSERT_SQL);
            pstmt.setString(1, user.getName());
            pstmt.setInt(2, user.getAge());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(null, pstmt, conn);
        }
    }
    public void update(User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(UPDATE_SQL);
            pstmt.setInt(1, user.getAge());
            pstmt.setString(2, user.getName());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(null, pstmt, conn);
        }
    }
    public void delete(int age) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(DELETE_SQL);
            pstmt.setInt(1, age);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(null, pstmt, conn);
        }
    }
    public List<User> selectAll() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<User> userList = new ArrayList<>();
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(SELECT_SQL);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt(1));
                user.setName(rs.getString(2));
                user.setAge(rs.getInt(3));
                userList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(rs, pstmt, conn);
        }
        return userList;
    }
}
public class User {
    private int id;
    private String name;
    private int age;
    // 省略getter、setter方法
}

6. PrepareStatement CRUD

PreparedStatement是一种预编译的Statement,它可以通过占位符的方式来替换SQL语句中的参数,避免了SQL注入的危险。下面是一个使用PreparedStatement进行CRUD操作的示例:

import java.sql.*;
public class PrepareStatementCRUD {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            // 插入数据
            String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "Tom");
            pstmt.setInt(2, 18);
            pstmt.executeUpdate();
            // 更新数据
            sql = "UPDATE users SET age = ? WHERE name = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, 20);
            pstmt.setString(2, "Tom");
            pstmt.executeUpdate();
            // 删除数据
            sql = "DELETE FROM users WHERE age = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, 20);
            pstmt.executeUpdate();
            // 查询数据
            sql = "SELECT * FROM users";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getInt(1) + ", " + rs.getString(2) + ", " + rs.getInt(3));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(rs, pstmt, conn);
        }
    }
}

以上就是关于JDBC入门、抽取工具类、Statement CRUD、演练CRUD、Dao模式(声明与实现分开)、PrepareStatement CRUD的详细介绍和代码示例。通过学习这些内容,可以让我们更好地掌握JDBC的使用和开发技巧,从而更好地应用到实际的项目中。

到此这篇关于如何使用JDBC连接数据库并执行SQL语句的文章就介绍到这了,更多相关JDBC连接数据库内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章