public class MysqlUpdate {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Connection connection = null;
PreparedStatement parestatement = null;
String user = "root";
String password = "root";
String url = "jdbc:mysql://localhost/bj206?characterEncoding=utf8";
try {
String id,name,age,email, gender, sql;
int lines;
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, user, password);
System.out.println("连接成功!");
System.out.println("现在是修改操作");
//修改数据
System.out.println("输入修改用户id:");
id = scan.next();
System.out.println("输入修改后的用户姓名:");
name = scan.next();
sql = "update users set name=? where id = ?";
parestatement = connection.prepareStatement(sql);
parestatement.setString(1, name);
parestatement.setString(2, id);
lines = parestatement.executeUpdate();
if (lines > 0) {
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
//添加数据
System.out.println("现在是添加操作");
System.out.println("输入添加用户姓名:");
name = scan.next();
System.out.println("输入添加用户年龄:");
age = scan.next();
System.out.println("输入添加用户邮箱:");
email = scan.next();
System.out.println("输入添加用户性别:");
gender = scan.next();
sql = "insert into users(id,name,age,email,gender)"
+ " values(null,?,?,?,?);";
parestatement = connection.prepareStatement(sql);
parestatement.setString(1, name);
parestatement.setString(2, age);
parestatement.setString(3, email);
parestatement.setString(4, gender);
lines = parestatement.executeUpdate();
if (lines > 0) {
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
//删除数据
System.out.println("现在是删除操作");
System.out.println("输入要删除用户id:");
id = scan.next();
//站位符?
sql = "delete from users where id = ?;";
parestatement = connection.prepareStatement(sql);
//给占位符赋值,要在运行前修改,第一个参数是第几位?
//,第二个参数是赋的值(注意是从1开始)
parestatement.setString(1, id);
//执行操作,返回影响的行数
lines = parestatement.executeUpdate();
if (lines > 0) {
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(parestatement != null)
try {
parestatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(connection != null)
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(scan != null)
scan.close();
}
}
mysql的增删改
最新推荐文章于 2022-03-12 16:07:21 发布