温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在JDBC中使用Statement对数据库进行修改

发布时间:2021-03-16 16:15:01 来源:亿速云 阅读:174 作者:Leah 栏目:编程语言

这期内容当中小编将会给大家带来有关怎么在JDBC中使用Statement对数据库进行修改,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

获取数据连接后,即可对数据库中的数据进行修改和查看。使用Statement 接口可以对数据库中的数据进行修改

/**
 * 获取数据库连接,并使用SQL语句,向数据库中插入记录
 */
package com.pack03;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class TestStatement {

 //***************************该方法用于获取数据库连接*****************************
 public static Connection getConnection() throws Exception {
  // 1.将配置文件中的连接信息获取到Properties对象中
  InputStream is = 
    TestStatement.class.getClassLoader().getResourceAsStream("setting.properties");

  Properties setting = new Properties();
  setting.load(is);

  // 2.从Properties对象中读取需要的连接信息
  String driverName = setting.getProperty("driver");
  String url = setting.getProperty("url");
  String user = setting.getProperty("user");
  String password = setting.getProperty("password");

  // 3.加载驱动程序,即将数据库厂商提供的Driver接口实现类加载进内存;
  // 该驱动类中的静态代码块包含有注册驱动的程序,在加载类时将被执行
  Class.forName(driverName);

  // 4.通过DriverManager类的静态方法getConnection获取数据连接
  Connection conn = DriverManager.getConnection(url, user, password);
  
  return conn;
 }
 
 
 //************************该方法用于执行SQL语句,修改数据库内容*************************
 public static void testStatement( String sqlStatement ) {
  
  Connection conn = null;
  Statement statement = null;
  
  try {
   //1.获取到数据库的连接
   conn = getConnection();
   
   //2.用Connection中的 createStatement()方法获取 Statement 对象
   statement = conn.createStatement();
   
   //3.调用 Statement 对象的 executeUpdate()方法,执行SQL语句并修改数据库
   statement.executeUpdate( sqlStatement );
   
  } catch (Exception e) {
   
   e.printStackTrace();
   
  } finally {
   
   //4.关闭Statement对象
   if(statement != null) {
    try {
     statement.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
   
   //5.关闭 Connection对象
   if(conn != null) {
    try {
     conn.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
  }
 }
 
 public static void main(String[] args) {
  
  
  String sqlInsert = "insert into tab001 values( 3, '小明3' )"; //插入语句
  String sqlUpdate = "update tab001 set name='王凯' where id=1"; //修改语句
  String sqlDelete = "delete from tab001 where id=2"; //删除语句
  //对于Statement对象,不能执行select语句
  
  testStatement( sqlInsert );
  testStatement( sqlUpdate );
  testStatement( sqlDelete );
 }
}

上述就是小编为大家分享的怎么在JDBC中使用Statement对数据库进行修改了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI