首先先要oracle的下载驱动包
然后将classes12.jar导入到eclipse中的项目中
然后创建如下工具类:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
private static String driver = "oracle.jdbc.OracleDriver";
private static String url = "jdbc:oracle:thin:@localhost:orcl";//如果oracle装在本机,也可以输入@ip地址
private static String user = "scott";//输入自己设置的账号
private static String password = "root";//输入自己设置的密码
static{
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection(){
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/*
* 执行java程序:
* java -Xms100M -Xmx200M HelloWorld
*/
public static void release(Connection conn, Statement st, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
rs = null;//垃圾回收: 是否可以通过代码干预垃圾回收??
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
st = null;//垃圾回收: 是否可以通过代码干预垃圾回收??
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
conn = null;//垃圾回收: 是否可以通过代码干预垃圾回收??
}
}
}
}
然后再创建一个测试类来调用它
public class test{
public static void main(String args[]){
JDBCUtils.getConnection();
}
}
如果没报错 证明连接没有问题了