java连接orcale数据库示例分享
database.properties
jdbc.driver_class=oracle.jdbc.driver.oracledriver
jdbc.connection.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.connection.username=scott
jdbc.connection.password=tiger
configmanager.java
import java.io.ioexception;
import java.io.inputstream;
import java.util.properties;
//读取配置文件(属性文件)的工具类
public class configmanager {
private static configmanager configmanager;
// properties.load(inputstream);读取属性文件
private static properties properties;
// 在构造工具类时,进行配置文件的读取
private configmanager() {
string configfile = "database.properties";
properties = new properties();
inputstream is = configmanager.class.getclassloader()
.getresourceasstream(configfile);
try {
// 读取配置文件
properties.load(is);
is.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
// 通过单例模式设置实例化个数
public static configmanager getinstance() {
if (configmanager == null) {
configmanager = new configmanager();
}
return configmanager;
}
// 通过key获取对应的value
public string getstring(string key) {
return properties.getproperty(key);
}
}
basedao.java
import java.sql.connection;
import java.sql.drivermanager;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;
import java.sql.statement;
import com.book.util.configmanager;
//基类:数据库操作通用类
public class basedao {
protected connection conn;
protected preparedstatement ps;
protected statement stmt;
protected resultset rs;
// 获取数据库连接
public boolean getconnection() {
// // 读取配置信息
string driver = configmanager.getinstance().getstring(
"jdbc.driver_class");
string url = configmanager.getinstance().getstring(
"jdbc.connection.url");
string username = configmanager.getinstance().getstring(
"jdbc.connection.username");
string password = configmanager.getinstance().getstring(
"jdbc.connection.password");
// 加载jdbc驱动
try {
class.forname(driver);
// 与数据库建立连接
conn = drivermanager.getconnection(url, username, password);
} catch (classnotfoundexception e) {
return false;
} catch (sqlexception e) {
return false;
}
return true;
}
// 增删改的通用方法
public int executeupdate(string sql, object[] params) {
int updaterows = 0;
getconnection();
try {
ps = conn.preparestatement(sql);
// 填充占位符
for (int i = 0; i < params.length; i++) {
ps.setobject(i + 1, params[i]);
system.out.println(i + 1 + "---" + params[i]);
}
system.out.println(sql);
updaterows = ps.executeupdate();
} catch (sqlexception e) {
e.printstacktrace();
}
return updaterows;
}
// 查询
public resultset executesql(string sql, object[] params) {
getconnection();
try {
ps = conn.preparestatement(sql);
// 填充占位符
for (int i = 0; i < params.length; i++) {
ps.setobject(i + 1, params[i]);
}
rs = ps.executequery();
} catch (sqlexception e) {
e.printstacktrace();
}
return rs;
}
// 关闭资源
public void closeall(){
try {
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
} catch (sqlexception e) {
e.printstacktrace();
}
}
}