JDBC封装增删改操作

JDBC封装增删改操作_第1张图片JDBC封装增删改操作_第2张图片

package com.utils;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * @author hrui
 * @date 2023/10/13 13:49
 */
public class DBUtils {
    private static ResourceBundle bundle=ResourceBundle.getBundle("jdbc");
    private static String driver=bundle.getString("jdbc.driver");
    private static String url=bundle.getString("jdbc.url");
    private static String username=bundle.getString("jdbc.username");
    private static String password=bundle.getString("jdbc.password");

    static{
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }
    
    //获取连接也可以合并掉
    public static int update(String sql,Object...args){
        Connection conn =null;
        PreparedStatement ps=null;
        int count=0;
        try {
            conn = DBUtils.getConnection();
            ps = conn.prepareStatement(sql);
            for(int i=0;i

测试

public class Test {
    public static void main(String[] args) throws SQLException {
//        String sql="insert into customers(id,name,email,birth,photo) values(null,?,?,?,null)";
//        DBUtils.update(sql,"小明","[email protected]","2022-02-02");
        String sql="update customers set name=? where id=?";
        int count = DBUtils.update(sql,"小王", 19);
        System.out.println(count);
    }
}

你可能感兴趣的:(java,数据库,开发语言)