当前位置 : 主页 > 编程语言 > c++ >

jdbc数据库连接

来源:互联网 收集:自由互联 发布时间:2021-06-30
gistfile1.txt public class DBHelper {private Connection conn;private PreparedStatement ps;private ResultSet rs;private static final String DRIVER="com.mysql.jdbc.Driver";private static final String URL="jdbc:mysql://localhost:3306/housedb";
gistfile1.txt
public class DBHelper {
	private  Connection conn;
	private  PreparedStatement ps;
	private  ResultSet rs;
	private static  final String DRIVER="com.mysql.jdbc.Driver";
	private static  final String  URL="jdbc:mysql://localhost:3306/housedb";
	private static  final String USER="root";
	private static  final String PWD="root";
	//加载驱动
	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	//打开连接
	private void  openConnection()throws ClassNotFoundException,SQLException {
		if(conn==null  || conn.isClosed()) {
			conn=DriverManager.getConnection(URL, USER, PWD);
		}
	}
	//关闭连接
	public  void close()throws SQLException{
		if(rs!=null) rs.close();
		if(ps!=null) ps.close();
		if(conn!=null) conn.close();
	}
	//增删改辅助方法
	public int executeUpdate(String sql,Object...obj)throws ClassNotFoundException,SQLException {
		openConnection();
		ps=conn.prepareStatement(sql);
		setParams(obj);
		return ps.executeUpdate();
	}
	//为占位符赋值
	private void setParams(Object...obj)throws ClassNotFoundException,SQLException {
		if(obj!=null && obj.length>0) {
			for (int i = 0; i < obj.length; i++) {
				ps.setObject(i+1, obj[i]);
			}
		}
	}
	//查询的辅助方法
	public ResultSet executeQuery(String sql,Object...obj)throws ClassNotFoundException,SQLException {
		openConnection();
		ps=conn.prepareStatement(sql);
		setParams(obj);
		return ps.executeQuery();
	}
}
上一篇:Http 请求工具类
下一篇:win7 开启wifi
网友评论