JAVASE下,关于JDBC功能封装的Utils类(适合未接触框架的初学者)

        在初学者练习和使用JDBC时,在代码中会反复连接数据库。从而出现严重的代码冗余,该文对JDBC代码进行简单的封装供大家使用。

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class MysqlConnection {

	/**
	定义getConnection()方法来获取Connection的对象,方便增删改查方法直接使用。
	*/
	private Connection getConnection() throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver"); 
		Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:????/"数据库名"?characterEncoding=UTF-8","Mysql账号", "Mysql密码");
		return conn;
	}
	
	/**
	增删改查功能,都是传入sql命令和sql命令中占位符的值。
	*/
	public static ResultSet MysqlSearch(String sql,String ... args) throws ClassNotFoundException, SQLException {
		Connection conn=getConnection();	//获取conn对象
		PreparedStatement ps=(PreparedStatement) conn.prepareStatement(sql);	//执行sql命令
		for (int i=0;i<args.length;i++) {		//利用循环给占位符赋值
			ps.setString(i+1, args[i]);
		}
		ResultSet rs=ps.executeQuery();
		return rs;		//返回ResultSet类型的值
	}
	
	public static void MysqlAdd(String sql,String ... args) throws ClassNotFoundException, SQLException {
		Connection conn=getConnection();
		PreparedStatement ps2=(PreparedStatement) conn.prepareStatement(sql);
		for (int i=0;i<args.length;i++) {
			ps2.setString(i+1, args[i]);
		}
		ps2.executeUpdate();
	}
	
	public static void MysqlDel(String sql,String ... args) throws ClassNotFoundException, SQLException {
		Connection conn=getConnection();
		PreparedStatement ps2=(PreparedStatement) conn.prepareStatement(sql);
		for (int i=0;i<args.length;i++) {
			ps2.setString(i+1, args[i]);
		}
		ps2.executeUpdate();
	}
	
	public static void MysqlUpdate(String sql,String ... args) throws ClassNotFoundException, SQLException {
		Connection conn=getConnection();
		PreparedStatement ps2=(PreparedStatement) conn.prepareStatement(sql);
		for (int i=0;i<args.length;i++) {
			ps2.setString(i+1, args[i]);
		}
		ps2.executeUpdate();
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值