数据库的连接程序
Java代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DBBean {
private Connection con = null;
private Statement stmt;
private ResultSet rs;
public DBBean() {
}
// 得到连接
public Connection getConnextion() throws Exception {
// 连接数据库的url
String url = "jdbc:oracle:thin:@10.2.104.50:1521:orcl";
// 用户名
String dbuser = "scott";
// 口令
String dbpass = "a123456";
if (con == null) {
// 加载驱动程序,参数是驱动程序的名字
Class.forName("oracle.jdbc.driver.OracleDriver");
// 建立连接,第一个参数是url
// 第二个参数是用户名,第三个参数是口令
con = DriverManager.getConnection(url, dbuser, dbpass);
}
return con;
}
// 执行有结果集返回的sql语句
public ResultSet executeQuery(String sql) throws Exception {
con = getConnextion();
if (con == null)
throw new Exception("没有连接对象可用");
// 创建语句对象
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
return rs;
}
// 执行更新语句
public int executeUpdate(String sql) throws Exception {
con = getConnextion();
if (con == null)
throw new Exception("没有连接可用");
// 创建语句对象
stmt = con.createStatement();
// 执行sql语句
return stmt.executeUpdate(sql);
}
public void close() {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
}
try {
stmt.close();
} catch (Exception e) {
}
try {
con.close();
} catch (Exception e) {
}
}
public static void main(String[] args) throws Exception {
String sql = "select * from users";
ResultSet rs = new DBBean().executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
}
作者“lw4135”
补充:软件开发 , Java ,