1、dataSource.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
username=username
password=password
2、代码示例
package com.example;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUtil {
/** 数据库驱动 */
private static String driver;
/** 数据库连接url */
private static String url;
/** 用户名 */
private static String username;
/** 密码 */
private static String password;
static {
// 创建properties对象获取属性文件的内容
Properties properties = new Properties();
// 获取属性文件的读取流对象
InputStream is = JdbcUtil.class.getResourceAsStream("/dataSource.properties");
try {
// 加载属性配置文件
properties.load(is);
// 获取jdbc参数
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
// 加载驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* DML操作
*
* @param sql sql语句
* @param objs 占位参数
* @return 影响的结果行数
*/
public static int executeDML(String sql, Object... objs) {
// 创建连接对象
Connection conn = getConnection();
// 创建sql命令对象
PreparedStatement ps = getPreparedStatement(sql, conn);
try {
// 手动提交事务
conn.setAutoCommit(false);
// 给占位符赋值
for (int i = 0; i < objs.length; i++) {
ps.setObject(i + 1, objs[i]);
}
int i = ps.executeUpdate();
conn.commit();
return i;
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
// 关闭资源
close(ps);
close(conn);
}
// 返回结果
return -1;
}
/**
* 获取Connection对象
*
* @return Connection对象
*/
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 获取PreparedStatement对象
*
* @param sql sql语句
* @param conn Connection连接对象
* @return PreparedStatement实例
*/
public static PreparedStatement getPreparedStatement(String sql, Connection conn) {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ps;
}
/**
* 获取Statement对象
*
* @param conn Connection连接对象
* @return Statement实例
*/
public static Statement getStatement(Connection conn) {
Statement stmt = null;
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stmt;
}
/**
* 关闭资源
*
* @param autoCloseable AutoCloseable接口实现类
*/
public static void close(AutoCloseable autoCloseable) {
if (autoCloseable != null) {
try {
autoCloseable.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}