` // 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