JDBC使用Statement修改数据库

时间:2018-08-20
这篇文章主要为大家详细介绍了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 );
 }
}

注:希望与各位读者相互交流,共同学习进步。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。