package com.zhaobp.db;
import java.io.*;
import java.sql.*;
public class DBConn {
public static String driver;//定义驱动
public static String url;//定义URL
public static String user;//定义用户名
public static String password;//定义密码
public static Connection conn;//定义连接
public static Statement stmt;//定义STMT
public ResultSet rs;//定义结果集
//设置CONN
static{
try {
driver="oracle.jdbc.driver.OracleDriver";
url="jdbc:oracle:thin:@localhost:1521:orcl";
user="scott";
password="tiger";
Class.forName(driver);
conn = DriverManager.getConnection(url,user,password);
System.out.println("-------连接成功------");
} catch(ClassNotFoundException e) {
e.printStackTrace();
System.err.println("db: " + e.getMessage());
} catch(SQLException e) {
System.err.println("db.getconn(): " + e.getMessage());
}
}
//构造函数,默认加裁配置文件为jdbc.driver
public DBConn(){
this.conn=this.getConn();
}
//返回Conn
public Connection getConn(){
return this.conn;
}
//执行插入
public void doInsert(String sql) {
try {
stmt = conn.createStatement();
int i = stmt.executeUpdate(sql);
} catch(SQLException e) {
System.err.println("db.executeInset:" + e.getMessage());
}finally{
}
}
//执行删除
public void doDelete(String sql) {
try {
stmt = conn.createStatement();
int i = stmt.executeUpdate(sql);
} catch(SQLException e) {
System.err.println("db.executeDelete:" + e.getMessage());
}
}
//执行更新
public void doUpdate(String sql) {
try {
stmt = conn.createStatement();
int i = stmt.executeUpdate(sql);
} catch(SQLException e) {
System.err.println("db.executeUpdate:" + e.getMessage());
}
}
//查询结果集
public ResultSet doSelect(String sql) {
try {
conn=DriverManager.getConnection(url,user,password);
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println("取得结果集啊:"+sql);
} catch(SQLException e) {
System.err.println("db.executeQuery:会是这个吗 " + e.getMessage());
}
return rs;
}
/**
*关闭数据库结果集,数据库操作对象,数据库链接
@Function: Close all the statement and conn int this instance and close the parameter ResultSet
@Param: ResultSet
@Exception: SQLException,Exception
**/
public void close(ResultSet rs) throws SQLException, Exception {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
}
/**
*关闭数据库操作对象,数据库连接对象
* Close all the statement and conn int this instance
* @throws SQLException
* @throws Exception
*/
public void close() throws SQLException, Exception {
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
}
//测试类
// public static void main(String []args){
// DBConn db=new DBConn();
// db.getConn();
// db.doInsert("insert into user (username,password) values('zhoabp','111')");
//
// }
}
jsp+servlet+javabean案例
需积分: 10 110 浏览量
2017-03-01
19:01:21
上传
评论 1
收藏 1.08MB ZIP 举报
两两翅膀
- 粉丝: 11
- 资源: 27