JDBC与MySQL数据库的更新、添加与删除操作

Statement对象调用方法

public int executeUpdate(String sqlStatement);

通过参数sqlStatement指定的方式实现对数据库表中记录的更新、添加和删除操作。
❶更新
update 表 set 字段 = 新值 where <条件句>
❷添加
insert into 表(字段列表) values (对应的具体的记录)
或:
insert into 表 values (对应的具体的记录)
❸删除
delete from 表名 where <条件子句>
下述SQL语句将mess表中name值为“张三”的记录的height字段的值更新为1.77:

update mess set height = 1.77 where name = '张三'

下述SQL语句将想mess表中添加两条新的记录(可以批次插入多条记录,记录之间用逗号分隔):

insert into mess values 
	('R1008','将林','2010-12-20',1.66),('R1008','秦仁','2010-12-20',1.66)

下述SQL语句将删除mess表中的number字段值为’R1002’的记录:

delete from mess where number = 'R1002'

注:需要注意的是,当返回结果集后,没有立即输出结果集的记录,而接着执行了更新语句,那么结果集就不能输出记录了。要想输出记录就必须重新返回结果集。

下面的例子向mess插入两条记录

import java.sql.*;
public class Example11_4 {
	public static void main(String[] args) {
		Connection con;
		Statement sql;
		ResultSet rs;
		con = GetDBConnection.connectDB("students", "root", "123");
		if(con == null)  return;
		String jilu = "('R11','将三','2000-10-23',1.66),"+
						"('R10','李武','1989-7-22',1.76)";
		String sqlStr = "insert into mess values "+jilu;
		try {
			sql = con.createStatement();
			int ok = sql.executeUpdate(sqlStr);
			rs = sql.executeQuery(sqlStr);
			while(rs.next()) {
				String number = rs.getString(1);
				String name = rs.getString(2);
				Date date = rs.getDate(3);
				float height = rs.getFloat(4);
				System.out.printf("%s\t",number);
				System.out.printf("%s\t",name);
				System.out.printf("%s\t", date);
				System.out.printf("%.2f\n", height);
			}
		con.close();
		}
		catch(SQLException e) {
			System.out.println(e);
		}
	}
}
class GetDBConnection {
	public static Connection connectDB(String DBName, String id, String p) {
		Connection con = null;
		String uri = "jdbc:mysql://localhost:3306/"+
		DBName+"?useSSL=false&characterEncoding=utf-8";
		try {
			Class.forName("com.mysql.jdbc.Driver");
		}
		catch(Exception e) {}
		try {
			con = DriverManager.getConnection(uri, id, p);
		}
		catch(SQLException e) {}
		return con;
	}
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值