jdbc mysql update语句_java常用知识:jdbc练习update语句

package jdbc;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class Demo02jdbc {

public static void main(String[] args) {

Connection conn =null;

Statement stmt =null;

try {

Class.forName("com.mysql.jdbc.Driver");

String sql = "update stu_account set balance = 1500 where id = 3";

conn = DriverManager.getConnection("jdbc:mysql://服务器:端口/数据库名字", "账号", "密码");

stmt = conn.createStatement();

int count = stmt.executeUpdate(sql);

System.out.println(count);

if(count > 0){

System.out.println("执行成功");

}else{

System.out.println("执行失败");

}

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

}finally{

if(stmt!=null){

try {

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if(conn!=null){

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 中可以使用 JDBCJava 数据库连接)API 操作数据库,其中包含了各种对数据库进行操作的方法,包括更新操作。MySQLupdate 语句用于修改表中的数据。下面是 Java 中使用 JDBCMySQL 数据库进行 update 操作的基本步骤: 1. 加载数据库驱动程序(例如 com.mysql.jdbc.Driver)。 2. 建立与数据库的连接(使用 DriverManager.getConnection(url,user,password) 方法)。 3. 创建 Statement 或者 PreparedStatement 对象。 4. 使用 Statement 或者 PreparedStatement 对象执行 SQL 语句(例如 "update table_name set column_name1 = value1, column_name2 = value2 where condition")。 5. 关闭 Statement、PreparedStatement 和 Connection 对象。 下面是一个使用 PreparedStatement 对象执行 update 语句的例子: ``` import java.sql.*; public class UpdateExample { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/test"; static final String USER = "root"; static final String PASS = "123456"; public static void main(String[] args) { Connection conn = null; PreparedStatement stmt = null; try{ Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL,USER,PASS); String sql = "UPDATE employees SET age=? WHERE id=?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, 35); stmt.setInt(2, 1); int rows = stmt.executeUpdate(); System.out.println(rows + " row(s) updated."); stmt.close(); conn.close(); }catch(SQLException se){ se.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ } try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值