通过Statement接口实现数据库的更新操作
来源:互联网 发布:超级基因优化液大结局 编辑:程序博客网 时间:2024/05/16 03:05
Statement接口位于java.sql.Statement下,想要对数据库执行更新操作,需要通过以下步骤
①获取了数据库连接并创建需要被执行的sql语句(sql语句为String型)
②使用Connection对象中的createStatement()方法获取用于执行sql语句的Statement对象
③调用刚刚获取到的Statement对象中的executeUpdate(String sql)方法执行sql语句
由于通过Statement接口中的executeUpdate(String sql)方法只能对数据库进行增、删、改操作,所以经过了如上的三个步骤之后,就能对数据库进行INSERT,UPDATE
,DELETE操作了;同时,在使用Statement接口对数据库进行操作时需要注意以下几点
①Connection与Statement都是应用程序与数据库的连接资源,在执行完相应的操作之后,一定要关闭
②为了防止在执行对更新操作的时候出现了异常而导致没有关闭Connection与Statement,他们的关闭操作需要在finally中执行
③关闭的顺序也是有讲究的,总结为四个字:先获后关,即先关闭后获取的,所以应该先关闭Statement后关闭Connection
下面是通过Statement接口实现数据库更新的具体的代码:
import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;import java.util.Properties;import org.junit.Test;public class Teststatement {@Test public void testStatement() throws Exception{//利用Statement进行更新操作 Connection con = null; Statement state = null; try{ // 1、获取数据库连接 con = getConnection(); // 2、生成插入的sql语句 String sql = "INSERT INTO animal (id,name,age) VALUES (1,'cat',3)"; // 3、获取操作SQL语句的Statement对象 state = con.createStatement(); // 4、调用Statement对象的executeUpdate(String aql)方法来执行sql语句 state.executeUpdate(sql); }catch(Exception e){ e.printStackTrace(); }finally{ //5、关闭Statement对象 if(con != null){ try { state.close(); } catch (Exception e) { e.printStackTrace(); } } //6、关闭数据库连接 if(con != null){ con.close(); } } } public Connection getConnection() throws Exception{//建立数据库连接 String driverclass = null; String url = null; String user = null; String password = null; Properties properties = new Properties(); InputStream in = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties"); properties.load(in); driverclass = properties.getProperty("driver"); url = properties.getProperty("jdbcurl"); user = properties.getProperty("user"); password = properties.getProperty("password"); Class.forName(driverclass); return DriverManager.getConnection(url, user, password); }}
当然了。。上面的代码也可以优化一下,让其可以实现INSERT、UPDATE、DELETE三种操作,只需要将testStatement中的sql变量变为形参,在需要执行SQL语句时传入语句即可。。我就不写了- -
阅读全文
0 0
- 通过Statement接口实现数据库的更新操作
- jdbc使用 Statement 接口实现更新数据操作
- JDBC :通过 Statement 执行数据表的更新操作
- JDBC:通过 Statement 执行更新操作
- JDBC--使用statement接口实现更新数据
- 使用 Statement 接口实现添加数据操作
- Statement语句实现数据库的增删改查操作
- JDBC_使用 Statement 执行更新操作(基于oracle数据库)
- JDBC Statement接口实现的execute方法
- JDBC利用Statement接口实现增删改操作
- jdbc03.使用Statement 接口实现增/删/改操作
- jdbc使用 Statement 接口实现添加数据操作小例子
- jdbc使用 Statement 接口实现删除数据操作
- 使用PrepareStatement接口,实现数据表的更新操作
- 使用PrepareStatement接口,实现数据表的更新操作
- JDBC--Statement(更新操作)
- JDBC通过Statement执行操作
- Java数据库编程---Statement接口
- 安装完Linux后,如何启动新添加的网卡
- 恢复使用win32 disk imager 制作的启动盘
- crond和crontab详解
- hihoCoder #1014 Trie树
- Docker环境 dockerUI redis mysql zookeeper安装使用
- 通过Statement接口实现数据库的更新操作
- 035-Java-026
- nginx+vsftpd搭建图片服务器
- 权益分发
- 下拉选为12个月 默认选择当前月 HTML+JS实现方式
- java克隆对象
- Wince对数据库操作,出现 对表达式求值导致溢出。 [ Name of function (if known) = ]
- 丑数
- Android产品研发(二十五)-->MVC/MVVM/MVP简单理解