1、创建项目
新建jdbc.properties文件
jdbc.name=scott2.编写连接数据库类
jdbc.pwd=tiger
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
package com.cd.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCConnection {
private static String name;
private static String pwd;
private static String driver;
private static String url;
private static Connection connection ;
private static PreparedStatement ps ;
private static ResultSet rs ;
static{
try {
InputStream inStream = JDBCConnection.class.getResourceAsStream("/jdbc.properties");
Properties properties = new Properties();
properties.load(inStream);
name=properties.getProperty("jdbc.name");
pwd=properties.getProperty("jdbc.pwd");
driver=properties.getProperty("jdbc.driver");
url=properties.getProperty("jdbc.url");
Class.forName(driver);
} catch (Exception e) {
throw new RuntimeException("读取数据区文件异常!", e);
}
}
public static Connection getconn(){
try {
connection = DriverManager.getConnection(url, name, pwd);
System.out.println("数据库连接成功"+connection);
} catch (SQLException e) {
throw new RuntimeException("数据库连接异常",e);
}return connection;
}
public static void close(){
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JDBCConnection.getconn();
JDBCConnection.close();
}
}