📄 dboper.java
字号:
package comm;
import java.sql.*;
import java.io.*;
import java.util.*;
import oracle.jdbc.*; // 引用JDBC驱动包
public class DBOper {
private Connection conn = null;
private Statement stmt = null;
// 数据库连接
public void connectDB() throws Exception
{
String hostName = "localhost"; // 主机名或者IP地址
String portNumber = "1521"; // 端口号,默认为1521
String databaseSID = "oracledb"; // SID名称
// String userName = "devsys"; // 用户名
// String password = "devsys"; // 用户密码
String userName = "newsmanager"; // 用户名
String password = "newsmanager"; // 用户密码
String url = "jdbc:oracle:thin:@"+hostName+":"+portNumber+":"+databaseSID; // 连接字符串
System.out.println(url); // 打印连接字符串
try{
// 装载驱动程序
Class.forName("oracle.jdbc.driver.OracleDriver");
// 建立连接
conn = DriverManager.getConnection(url,userName,password);
}
catch (Exception e){
// 如果有异常,则抛出错误
System.out.println("=====Exception : DBOper connectDB() exception: " + e.getMessage());
}
}
// 获取数据库连接对象
public Connection getConnection() throws Exception
{
return conn;
}
// 执行查询,返回单一结果
public ResultSet getResultSet(String sql) throws SQLException
{
try{
// 如果数据库没有连接,则连接数据库
if(conn==null)
connectDB();
}
catch (Exception e){
throw new SQLException(e.getMessage());
}
// 如果语句为空,则创建语句
if(stmt ==null)
stmt =conn.createStatement();
// 执行查询,返回查询结果集
return stmt.executeQuery(sql);
}
// 添加、删除、更新操作
public void DataUpdate(String sql) throws SQLException
{
try
{
// 连接数据库
if(conn==null)
connectDB();
// 创建语句
if(stmt ==null)
stmt =conn.createStatement();
// 执行更新操作
stmt.executeUpdate(sql);
}
catch (Exception e)
{
throw new SQLException(e.getMessage());
}
}
// 关闭
public void close() throws SQLException
{
// 设置自动提交
conn.setAutoCommit(true);
// 关闭语句,关闭连接
if(stmt!=null) {stmt.close();stmt =null;}
if(conn!=null) {conn.close();conn =null;}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -