獲取數(shù)據(jù)連接后,即可對數(shù)據(jù)庫中的數(shù)據(jù)進行修改和查看。使用Statement 接口可以對數(shù)據(jù)庫中的數(shù)據(jù)進行修改,下面是程序演示。
/** * 獲取數(shù)據(jù)庫連接,并使用SQL語句,向數(shù)據(jù)庫中插入記錄 */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 { //***************************該方法用于獲取數(shù)據(jù)庫連接***************************** 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.加載驅(qū)動程序,即將數(shù)據(jù)庫廠商提供的Driver接口實現(xiàn)類加載進內(nèi)存; // 該驅(qū)動類中的靜態(tài)代碼塊包含有注冊驅(qū)動的程序,在加載類時將被執(zhí)行 Class.forName(driverName); // 4.通過DriverManager類的靜態(tài)方法getConnection獲取數(shù)據(jù)連接 Connection conn = DriverManager.getConnection(url, user, password); return conn; } //************************該方法用于執(zhí)行SQL語句,修改數(shù)據(jù)庫內(nèi)容************************* public static void testStatement( String sqlStatement ) { Connection conn = null; Statement statement = null; try { //1.獲取到數(shù)據(jù)庫的連接 conn = getConnection(); //2.用Connection中的 createStatement()方法獲取 Statement 對象 statement = conn.createStatement(); //3.調(diào)用 Statement 對象的 executeUpdate()方法,執(zhí)行SQL語句并修改數(shù)據(jù)庫 statement.executeUpdate( sqlStatement ); } catch (Exception e) { e.printStackTrace(); } finally { //4.關(guān)閉Statement對象 if(statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } //5.關(guān)閉 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對象,不能執(zhí)行select語句 testStatement( sqlInsert ); testStatement( sqlUpdate ); testStatement( sqlDelete ); }}
注:希望與各位讀者相互交流,共同學(xué)習(xí)進步。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點
疑難解答
圖片精選