eclipse中对数据库的 增删改 类的代码怎么写
1个回答
展开全部
以前写过一个jdbc的例子,比如user类有两个属性username和passwordprivate 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();
}
}
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();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询