java如何连接oracle数据库:
package com.wangjie.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
private static String driver;
private static String url;
private static String user;
private static String password;
static {
try {
Properties prop = new Properties();
prop.load(new FileInputStream("properties/jdbc.properties"));
driver = prop.getProperty("driver");
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
Class.forName(driver);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConn() {
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void closeConn(Connection conn, Statement state,
ResultSet result) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (state != null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (result != null) {
try {
result.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println(JDBCUtils.getConn());
}
@SuppressWarnings("unused")
private static void writeProperties() {
Properties pro = new Properties();
pro.setProperty("driver", "oracle.jdbc.driver.OracleDriver");
pro.setProperty("url", "jdbc:oracle:thin:@127.0.0.1:1521:orcl");
pro.setProperty("user", "joy");
pro.setProperty("password", "joy");
try {
File file = new File("properties/jdbc.properties");
file.createNewFile();
pro.store(new FileOutputStream(file),
"educational administration jdbc properties document.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
jdbc.properties配置文件内容如下:
#educational administration jdbc properties document.
#Wed Aug 22 21:47:46 CST 2012
user=joy
password=joy
url=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:orcl
driver=oracle.jdbc.driver.OracleDriver