帮我用java写姓名的增删改查,用mysql数据库,需要考虑数据的安全性和校验,姓名用String类型,数据表结构任意
时间: 2024-05-20 22:10:20 浏览: 48
好的,我明白了。以下是用Java编写姓名的增删改查代码,使用MySQL数据库,并考虑数据安全性和校验。
请注意,在编写代码时,请确保以下内容:
1. 必须使用try-catch块来捕获可能发生的异常。
2. 在与数据库对话时,需要使用关闭语句和连接语句来关闭数据库连接。
3. 考虑到数据安全性和校验,需要使用预处理语句。
增加数据:
public static void insertRecord(String name) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase","username","password");
String query = "INSERT INTO tablename(name) VALUES(?)";
pstmt = conn.prepareStatement(query);
pstmt.setString(1,name);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
pstmt.close();
conn.close();
}
}
删除数据:
public static void deleteRecord(String name) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase","username","password");
String query = "DELETE FROM tablename WHERE name=?";
pstmt = conn.prepareStatement(query);
pstmt.setString(1,name);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
pstmt.close();
conn.close();
}
}
修改数据:
public static void updateRecord(String oldName,String newName) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase","username","password");
String query = "UPDATE tablename SET name=? WHERE name=?";
pstmt = conn.prepareStatement(query);
pstmt.setString(1,newName);
pstmt.setString(2,oldName);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
pstmt.close();
conn.close();
}
}
查询数据:
public static void selectRecord() throws SQLException{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase","username","password");
stmt = conn.createStatement();
String query = "SELECT * FROM tablename";
rs = stmt.executeQuery(query);
while(rs.next()){
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs.close();
stmt.close();
conn.close();
}
}
请注意,在上面的代码中,请将“mydatabase”替换为您的数据库名称,“username”替换为您的数据库用户名,“password”替换为您的数据库密码,“tablename”替换为您的表名。
阅读全文