Eclipse连接数据库

//加载器
public void getConnection() {
	try {
		Class.forName("com.mysql.jdbc.Driver");
		conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/root", "root", "1234");
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	} catch (SQLException e) {
		e.printStackTrace();
	}
}
//增删改
public int execustSQL(String sql,Object... obj) {
	this.getConnection();
	int count = -1;
	try {
		this.pstmt = conn.prepareStatement(sql);
		for(int i=0;i<obj.length;i++) {
			this.pstmt.setObject(i+1, obj[i]);
		}
		pstmt.executeUpdate();
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return count;
}
//查询
public ResultSet executeQSL(String sql,Object... obj) {
	this.getConnection();
	try {
		this.pstmt = conn.prepareStatement(sql);
		for(int i=0;i<obj.length;i++) {
			pstmt.setObject(i+1, obj[i]);
		}
		rs = pstmt.executeQuery();
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return rs;
	
}
//关闭流
public void closeAll() {
	if(rs!=null) {
		try {
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	if(pstmt!=null) {
		try {
			pstmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

}
}
}

猜你喜欢

转载自blog.csdn.net/kai521314/article/details/83650182