[JAVA]修改数据库中数据
首先,创建一个名为test的数据库,库中创建一个student的表。将修改表中NAME字段中的”Tom”。
添加数据
*我将连接数据库,调用数据库和关闭资源分了三个方法,
*
/*
* 连接数据库方法
* */
public Connection getCconnection() throws Exception {
//数据信息
String user = "root";
String password = "1579886070";
String jdbcUrl = "jdbc:mysql://127.0.0.1:3360/test";
String driverClass = "com.mysql.jdbc.Driver";
//加载驱动
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
return connection;
}
然后我们建立主方法,在其中调用
public void testUpdate(){
Connection connection = null;
Statement statement = null;
try {
//连接数据库
connection = getCconnection();
//调用 Connection 对象的 createStatement() 方法获取Statement 对象
statement = connection.createStatement();
//准备SQL语句
String sql = "UPDATE student SET name = 'XiaoXin' WHERE id = 1";
//4.发送SQL语句:调用Statement 对象的 executeUpdate(sql)方法
statement.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}finally {
//调用关闭资源方法
getRelease(null, statement, connection);
}
}
在finally块中调用关闭资源的方法
/*
* 关闭资源方法
* */
public void getRelease(ResultSet resultSet,Statement statement,Connection connection){
if(resultSet != null){
try {
resultSet.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(statement != null){
try {
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行,执行完后查看数据表
好啦,将原本NAME中的”Tom”修改为”XiaoXin”了。
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 xiaoxin1218@qq.com
文章标题:[JAVA]修改数据库中数据
文章字数:304
本文作者:周信
发布时间:2019-10-13, 22:56:07
最后更新:2023-05-03, 10:25:35
原始链接:http://zx21.xyz/2019/10/13/JAVA-修改数据库中数据/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

