通过Statement接口实现数据库的更新操作

xiaoxiao2021-02-28  62

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语句时传入语句即可。。我就不写了- -
转载请注明原文地址: https://www.6miu.com/read-84823.html

最新回复(0)