数据库操作类DBHelper(Java版)

package com.uitl;

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

public class DBHelper {
	static Connection conn;
	static PreparedStatement ps;
	static ResultSet rs;
	static String driver = "com.mysql.jdbc.Driver";
	static String url = "jdbc:mysql://localhost:3306/newsmanagersystem?characterEncoding=UTF-8";// 连接字符串
	static String uname = "root";
	static String pwd = "";

	// 获取数据库连接
	public static Connection ConnDB() {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, uname, pwd);
		}catch (ClassNotFoundException e) {
			e.printStackTrace();
		}catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	// 查询(可变参数)
	public static ResultSet ExcuteQuery(String sql, Object... params) {
		conn = ConnDB();
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			// 设置问号值
			for (int j = 0; j < params.length; j++) {
				Object object = params[j];
				ps.setObject(j + 1, object);
			}
			//执行
			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	//增删改(可变参数)
	public static Boolean ExcuteNoQuery(String sql, Object... params) {
		conn = ConnDB();
		int i = 0;
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			// 设置问号值
			for (int j = 0; j < params.length; j++) {
				Object object = params[j];
				ps.setObject(j + 1, object);
			}
			i = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i > 0;
	}

	//释放资源
	public static void ClossResource() {
		if (rs != null) {
			try {
				rs.close();
				rs = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (ps != null) {
			try {
				ps.close();
				ps = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
				conn = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}


标题:数据库操作类DBHelper(Java版)
作者:Aiw
地址:http://tovi.top/articles/2021/12/30/1640831081010.html

    评论
    0 评论
avatar

取消