mysql的增删改

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();
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值