Java通用的增删改数据库的操作

Java通用的增删改数据库的操作

package com.sunyiJDBC01;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Description
 * @author sy email:869181257@qq.com
 * @version
 * @date Jan 19, 20218:46:33 PM
 */
public class ConnDb {
//将数据库连接需要的4个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接
	public static void getConnection() throws IOException, ClassNotFoundException, SQLException {
		//1.读取配置文件的4个基本信息
		InputStream is=ConnDb.class.getClassLoader().getResourceAsStream("jdnc.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);
		Connection conn=DriverManager.getConnection(url, user, password);
		System.out.println(conn);
		
	}
	
}

user=root
password=qweasdzxc
url=jdbc:mysql://localhost:3306/t6t7?serverTimezone=UTC
driverClass=com.mysql.cj.jdbc.Driver
#这个是在当前包下创建一个名字叫jdnc.properties的文件,
#相当于配置文件。这样好修改
增删改的代码
package com.demo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Description
 * @author sy email:869181257@qq.com
 * @version
 * @date Jan 19, 202110:11:05 PM
 */
public class 通用的增删改 {							 //可变的参数数量
			public static void update(String sql,Object ...args){		
				Connection conn = null;//				1.获取数据库的连接
				PreparedStatement pst=null;//				2.预编译sql语句,返回PreparedStatement的实例
				try {
					conn=ConnDb.getConnection();
					pst = conn.prepareStatement(sql);
					for (int i = 0; i < args.length; i++) {//					3.填充占位符
						pst.setObject(i+1, args[i]);//小心参数声明错误!!!!
					}
					pst.execute();//				4.执行
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					ConnDb.closeDb(null, pst, conn);	//关闭资源
				}
			}
			public static void main(String[] args) {
				String sql = "delete from emp where empno=?";
				update(sql,7369);
			}
}

如果此篇文章对你有帮助,请关注我,如果有问题,评论,我会及时回复的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值