` // dbhelp help类,封装数据库基本信息以及关闭资源的方法mysql
class DbHelp{ //数据库链接信息 public static String url = "jdbc:mysql://localhost:3306/blog"; public static String user = "root"; public static String password = "root"; public static String driver = "com.mysql.jdbc.Driver"; public static PreparedStatement ps = null; public static Connection conn = null; public ResultSet rs = null; //获取数据库链接的方法 public static void getConnection(){ try { Class.forName(driver); conn = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } // 关闭资源 public void close(){ try { ps.close(); conn.close(); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } // User实体类 public class User{ private int id; private String name; private String contact; private String telephone; private String email; private String remark; private String userName; private String address; @Override public String toString() { return "User [id=" + id + ", name=" + name + ", contact=" + contact + ", telephone=" + telephone + ", email=" + email + ", remark=" + remark + ", userName=" + userName + ", address=" + address+ "]"; } // get/set 方法 。。。。。。 } //数据库操做类 public class UserDemo extends DbHelp{ public User getUser(){ getConnection(); User user = new User(); String sql = "select * from t_sys_user where user_id = ?"; try{ ps = conn.prepareStatement(sql); // 设置参数,第一个问号的值为 8 ps.setInt(1,8) rs = ps.executeQuery(); while(rs.next()){ user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setContact(rs.getString("contact")); user.setEmail(rs.getString("email")); user.setRemark(rs.getString("remark")); user.setTelephone(rs.getString("telephone")); } }catch(SQLException e){ e.printStackTrace(); } //关闭资源 close(); return user; } } //测试方法 public static void main(String[] a){ UserDemo demo = new UserDemo(); User user = demo.get(); System.out.println(user.toString()); }
`sql