当前位置: 代码迷 >> Eclipse >> eclipse中对数据库的 增 删 改 类的代码如何写
  详细解决方案

eclipse中对数据库的 增 删 改 类的代码如何写

热度:678   发布时间:2016-04-23 01:18:33.0
eclipse中对数据库的 增 删 改 类的代码怎么写
本人刚接触Eclipse第3天,想做一个增删改的数据类 求各位大神指点。最好有代码 谢谢了各位大神

------解决方案--------------------
我以前写过一个jdbc的例子,比如user类有两个属性username和password
private String sql = "select password from user where username=?";
private String insert = "insert into user(username,password) values(?,?)";

public String getPwdByName(String username) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
User user = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "admin");
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
rs = pstmt.executeQuery(sql);
while (rs.next()) {
user = new User();
user.setUsername(rs.getString(1));
user.setPassword(rs.getString(2));
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

public void save(User u) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "admin");
pstmt = conn.prepareStatement(insert);
pstmt.setString(1, u.getUsername());
pstmt.setString(2, u.getPassword());
pstmt.executeUpdate();
//System.out.println(insert);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
  相关解决方案