加入收藏 | 设为首页 | 会员中心 | 我要投稿 晋中站长网 (https://www.0354zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

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

发布时间:2022-12-21 14:04:54 所属栏目:MySql教程 来源:未知
导读: Statement对象调用方法
public int executeUpdate(String sqlStatement);

通过参数sqlStatement指定的方式实现对数据库表中记录的更新、添加和删除操作。
?更新
update 表 set 字段 = 新值

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;
	}
}

(编辑:晋中站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!