数据库工具类 DBUtil

12 篇文章 0 订阅

数据库工具类 DBUtil

// 数据库工具类
public class DBUtil {
	    // 定义四个常量值
		private static final String DRIVER = "com.mysql.jdbc.Driver";
		private static final String URL = "jdbc:mysql:///java31?characterEncoding=utf8";
		private static final String USER = "root";
		private static final String PASSWORD = "root";
		// 定义JDBC常用类和接口
		private static Connection con = null;
		private static Statement st = null;
		private static PreparedStatement ps = null;
		private static ResultSet set = null;
		
		static {
			try {
				Class.forName(DRIVER);
				con = DriverManager.getConnection(URL, USER, PASSWORD);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 针对查询的功能
		public static ResultSet select(String sql,Object[] args) {
			//String sql2   =  "select * from account where u_name = ? and password = ?"; 
			try {
				// 获取预处理对象
				 ps = con.prepareStatement(sql);
				 // 使用sql语句中的占位符  ?
				 // 遍历数组
				 // 占位符 在sql中是有前后顺序的   u_name对应的问号 索引是 1 password对应的问号就是2
				 for (int i = 0; i < args.length; i++) {
					// 把问号提换成具体的数据
					ps.setObject(i+1, args[i]);
				}
			   // 执行sql语句 获取结果值
			   set = ps.executeQuery();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return set;
		}
		// 针对更新的功能  insert update delete  executeUpdate()
		public static int update(String sql,Object[] args) {
			// 获取预处理对象
			// 定义一个变量 用来记录印象数据库表的行数
			int count = 0;
			 try {
				ps = con.prepareStatement(sql);
				 // 使用sql语句中的占位符  ?
				 // 遍历数组
				 // 占位符 在sql中是有前后顺序的   u_name对应的问号 索引是 1 password对应的问号就是2
				 for (int i = 0; i < args.length; i++) {
					// 把问号提换成具体的数据
					ps.setObject(i+1, args[i]);
				}
			   // 执行sql语句 获取结果值
			   count = ps.executeUpdate();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 返回给调用处 
			return count;
		}	
		// 关闭连接的方法
		public static void closeAll() {
			// 关闭时 先关闭ResultSet
				if (set != null) {
					try {
						set.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				if (st != null) {
					try {
						st.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				if (con != null) {
					try {
						con.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
		}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值