package db;
// 1导包
import java.sql.*;
public class DB
{
private Connection con = null;
private Statement st = null;
private ResultSet rs = null;
private PreparedStatement pstmt = null;
public DB()
{
try
{
// 2加载驱动
Class.forName(DBConfig.JDBC_DRIVER);
// 3建立连接
con = DriverManager.getConnection(DBConfig.JDBC_URL,
DBConfig.JDBC_USRE, DBConfig.JDBC_PASSWORD);
// 4创建执行sql语句对象
st = con.createStatement();
System.out.println("DB int OK!");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
/**
* 增删改处理
*
* @param sql:增删改sql语句
* @return 操作影响行数
*/
public int update(String sql)
{
int res = 0;
System.out.println(sql);
try
{
res = st.executeUpdate(sql);
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
this.close(); // 释放资源
}
return res;
}
/**
* 查询
*
* @param sql
* @return
*/
public ResultSet query(String sql)
{
System.out.println(sql);
try
{
rs = st.executeQuery(sql);
}
catch (SQLException e)
{
e.printStackTrace();
}
return rs;
}
public ResultSet executeQuery(String preparedSql)
{
System.out.println(preparedSql);
try
{
pstmt = con.prepareStatement(preparedSql); // 得到PreparedStatement对象
rs = pstmt.executeQuery();
}
catch (SQLException e)
{
e.printStackTrace();
}
return rs;
}
/**
*执行增删改处理
* @param preparedSql:预编译的sql语句,里面可能包含?
* @param param:给预编译的sql语句中的?赋值,
* 并且数量位置一一对应,如过预编译的sql语句中没有?则param应该为null
* @return
*/
public int executeUpdate(String preparedSql, String[] param)
{
int num = 0;
/* 处理SQL,执行SQL */
try
{
// 得到数据库连接
pstmt = con.prepareStatement(preparedSql); // 得到PreparedStatement对象
if (param != null)
{
for (int i = 0; i < param.length; i++)
{
pstmt.setString(i + 1, param[i]); // 为预编译sql设置参数
}
}
num = pstmt.executeUpdate(); // 执行SQL语句
}
catch (SQLException e)
{
e.printStackTrace(); // 处理SQLException异常
}
finally
{
this.close(); // 释放资源
}
return num;
}
public int getCount(String tableName)
{
int res = 0;
String sql = "select count(*) as c from " + tableName;
rs = this.query(sql);
try
{
rs.next();
// res=rs.getInt("c");
res = rs.getInt(1);
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
this.close(); // 释放资源
}
return res;
}
/**
* 关闭
*/
public void close()
{
try
{
if (rs != null)
{
rs.close();
rs = null;
}
if (st != null)
{
st.close();
st = null;
}
if (con != null && !con.isClosed())
{
con.close();
con = null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public Connection getCon()
{
return con;
}
public static void main(String[] args)
{
new DB();
}
}
webQQ jsp项目
3星 · 超过75%的资源 需积分: 10 159 浏览量
2009-05-30
21:01:02
上传
评论
收藏 447KB RAR 举报
jonex
- 粉丝: 9
- 资源: 6
最新资源
- 农村信用社联合社计算机信息系统投产与变更管理办.docx
- 农村信用社联合社计算机信息系统数据管理办法.docx
- 利用SPSS作临床效度分析线上计算网站介绍-医学研究部统计谘.(医学PPT课件).ppt
- 利用Zabbix监控mysqldump定时备份数据库状态.docx
- 利用计算机解决问题的基本过程.doc
- 化工铁路通信工程总结.doc
- 北京大学网络教育软件工程作业.docx
- 医药公司(连锁店)计算机操作规程未新系统的自行按照旧制修改-新系统过制的编号加修模版.doc
- 医药公司(连锁店)计算机系统操作规程模版.doc
- 医药连锁门店计算机系统的操作和管理程序未新系统的自行按照旧制修改-新系统过制的编号加修模版.docx
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈