Oracle的JDBC连接工具类
public class JDBCUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try {
FileInputStream fileInputStream = new FileInputStream("src\\com\\llm\\test\\demo\\db.properties");
Properties prop = new Properties();
prop.load(fileInputStream);
driver = prop.getProperty("driver");
url = prop.getProperty("url");
username = prop.getProperty("username");
password = prop.getProperty("password");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void updateByString(String sql,Object[] objs){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < objs.length; i++) {
preparedStatement.setObject(i+1,objs[i]);
}
int i = preparedStatement.executeUpdate();
if (i > 0){
System.out.println("更新成功");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(connection,preparedStatement,null);
}
}
public static Connection getConnection(){
Connection conn=null;
try {
Class.forName(driver);//加载数据驱动
conn = DriverManager.getConnection(url, username, password);// 连接数据库
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("加载数据库驱动失败");
}catch(Exception e){
e.printStackTrace();
System.out.println("连接数据库失败");
}
return conn;
}
public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(ps!=null){
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/202484.html