获取数据连接后,即可对 数据库 中的数据进行修改和查看。使用statement 接口可以对数据库中的数据进行修改,下面是程序演示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
/** * 获取数据库连接,并使用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 ); } } |
注:希望与各位读者相互交流,共同学习进步。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://www.cnblogs.com/EarthPioneer/p/9501269.html
查看更多关于JDBC使用Statement修改数据库的详细内容...