1. 程式人生 > >java連線oracle資料庫以及相關資料庫操作

java連線oracle資料庫以及相關資料庫操作

package test.db;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.logging.Logger;

import net.sf.json.JSONObject;

public class JDBC2Oracle {
	private static Logger log = Logger.getLogger("oracledb");
	//static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設定日期格式
	public static void connect2db(){
		try{
			//1.載入對應資料庫驅動
			Class.forName("oracle.jdbc.driver.OracleDriver");
			//Class.forName("com.mysql.jdbc.Driver");
			//2.獲取資料庫連線
			String url = "jdbc:oracle:thin:@10.10.162.20:1521:dbroker";
			String username = "srmd";
			String password = "srmd";
			Global.coon = DriverManager.getConnection(url, username, password);
			log.info("資料庫連線成功!");
		}catch(Exception e){
			log.info("資料庫連線失敗!");
			e.printStackTrace();
			//System.exit(0);
		}

	}
	public static void insert2db(JSONObject tmpStudent){
		PreparedStatement pre = null;// 建立預編譯語句物件,一般都是用這個而不用Statement
	    try{
	    	//3.資料庫操作--增、刪、改
	    	String sql = "insert into students "
					+"(id, name, age, class)"
					+" values ("
					+tmpStudent.get("id").toString()+","
					+tmpStudent.get("name").toString()+","
					+tmpStudent.get("age").toString()+","
					+tmpStudent.get("class").toString()+"',"
					+")";
			pre = Global.coon.prepareStatement(sql);
			pre.executeUpdate();
			
	    }catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			//4.釋放資源
			try{
				if(pre!=null){
					pre.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}

	public static void query2db(){
		PreparedStatement pre = null;// 建立預編譯語句物件,一般都是用這個而不用Statement
	    ResultSet rs = null;// 建立一個結果集物件
	    try{
	    	//3.資料庫操作-查
			String sql = "select * from students";
			pre = Global.coon.prepareStatement(sql);
			rs = pre.executeQuery();
			
			ResultSetMetaData meta = rs.getMetaData();
			int colCnt = meta.getColumnCount();//列的個數
			
			while(rs.next()){
				for(int i = 1; i<=colCnt; i++){
					String colName = meta.getColumnName(i);//列名
					String value = rs.getString(colName);//列值
					System.out.println(colName+":"+value);
				}
			}
	    }catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			//4.釋放資源
			try{
				if(rs!=null){
					rs.close();
				}
				if(pre!=null){
					pre.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}


	public static void closedbconnect(){
		if(Global.coon!=null){
			try {
				Global.coon.close();
				System.out.println("資料庫連線已關閉!");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}