1. 程式人生 > >JDBC_使用 Statement 執行更新操作(基於oracle資料庫)

JDBC_使用 Statement 執行更新操作(基於oracle資料庫)

具體思路如下: 
* 通過JDBC向指定的資料表中插入一條記錄 
1.Statement:用於執行SQL語句物件 
1).通過Connection的createStatement()方法獲取 
2).通過executUpdate(sql)可以執行SQL語句 
3).傳入的sql語句可以是insert,update或者delete,但不能是select 
2.Connection,Statement都是應用程式和資料庫伺服器的連線資源,使用後一定要關閉 
需要在finally中關閉物件 
3.關閉的順序是先關閉後獲取的

這裡將連線資料庫的程式碼封裝成一個類JDBCToos 方便以後的呼叫 
JDBCTools.java

package com.atchance.jdbc;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCTools {

    public static void release(Statement statement, Connection con) throws SQLException{
        try {
            if
(statement != null) statement.close(); } catch (Exception e) { e.printStackTrace(); }finally{ if(con != null) con.close(); } } public static Connection getConnection() throws Exception{ String driverClass = "oracle.jdbc.driver.OracleDriver"
; String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL"; String user = "scott"; String password = "tiger"; Driver driver = (Driver)Class.forName(driverClass).newInstance(); Properties info = new Properties(); info.put("user", user); info.put("password", password); Connection connection = driver.connect(jdbcUrl,info); return connection; } }

之後在另一個檔案裡實現sql語句的增刪改 
JDBCTest1.java

package com.atchance.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import oracle.jdbc.*;
import oracle.jdbc.driver.*;

public class JDBCTest1 {

    public void update(String sql) throws SQLException{
        /**
         * 提取出函式實現資料庫的增刪改
         */
        Connection con = null;
        Statement statement = null;
        try {
            con = JDBCTools.getConnection();
            statement = con.createStatement();
            statement.execute(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JDBCTools.release(statement, con);
        }
    }
    public static void main(String[] arg) throws Exception{
        JDBCTest1 t1 = new JDBCTest1();
        String sql = "insert into student values('0999','姓名','男','湖南')";
        t1.update(sql);
    }
}

以上就是實現JDBC連線oracle資料庫進行增刪改三種操作的程式碼