开发可重用的数据库连接
来源:互联网 发布:五仁月饼知乎 编辑:程序博客网 时间:2024/04/29 00:58
1、定义该类需要用到的一些属性与实例
private static final String DRIVERCLASS="com.microsoft.jdbc.sqlserver.SQLServerDriver";
protect final String url="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=db_JSDQ10";
protect final String user="sa";
protect final String password="";
protect Connection conn;
2、负责加裁数据库驱动的静态方法
static{
try{
Class.forName(DRIVERCLASS);
}catch(ClassNotFoundException e){
System.out.println(" Load Class error.");
e.printStackTrace();
}
}
3、建立数据库的连接并设置自动提交模式
public boolean openConn(boolean autoCommint){
boolean isOpen=true;
try{
conn=DriverManager.getConnection(url, user, password);
if(!autoCommit)
conn.setAutoCommit(false);
}catch(SQLException e){
isOpen=false;
System.out.println(" Create connection error.");
e.printStackTrace();
}
}
4、关闭数据库连接
public boolean closeConn(){
boolean isCommit=true;
try{
conn.commit();
}catch(SQLException e){
isCommit=false;
System.out.println("Commit error.");
e.printStackTrace();
try{
conn.rollback();
}catch(SQLException e1){
System.out.println("Rollback error.");
e1.printStackTrace();
}
}final{
try{
stmt.close();
conn.close();
}catch(SQLException e){
System.out.println("Close Connection error.");
e.printStackTrace();
}
return isCommit;
}
}
5、获取数据库连接
public class TestJDBC extends JDBC{
public List<Object[]> selectBySQL(String sql){
List<Object[]> notes=new ArrayList<Object[]>();
this.openConn(true);
try{
this.stmt=conn.createStatement();
this.rs=stmt.executeQuery(sql);
int l=rs.getMetaData().getColumnCount();
while(rs.next()){
Object[] note=new Object[];
for(int i=0; i<l; i++){
note[i]=rs.getObject(i+1);
}
notes.add(note);
}
this.rs.close();
this.stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
this.closeConn();
return notes;
}
}
调用例:
List<Object[]> notes=testJDBC.selectBySQL("select * from tb_test_join");
for(int m=0; m<notes.size(); m++){
out.println("<tr align='center' bgcolor='#FFCC99'>");
Object[] note=notes.get(m);
for(int n=0; n<note.length; n++){
out.println("<td>"+note[n]+"</td>");
}
out.println("</tr>");
}
- 开发可重用的数据库连接
- 可重用的数据库连接框架
- 自行开发了个可重用的数据库连接框架
- 可重用的UI开发框架
- 可重用的SVG
- 用 PHP 开发健壮的代码: 编写可重用函数
- rails开发利器:google map 简单可重用的代码
- 可重用性的克服
- 可重用代码的艺术
- MENU可重用的子系统
- 创建可重用的Layout
- 可重用的代码块
- 子系统的可重用设计
- 开发出编写可重用、可扩展、可维护、灵活性高的代码需要经历遵循以下原则
- 如何把握可重用与不可重用的人才
- Visual Studio 2005:为开发小组创建可重用的项模板
- 简单的可重用的输入验证
- 软件可重用性的一点思考
- carewel地坪起砂处理剂
- Google 为 IE6 用户提供 Gmail 升级
- MySQL数据类型简介
- .net使用的两个很好的工具
- 哈希密码解密网址
- 开发可重用的数据库连接
- 求解数独
- 改变一下顺序,也许会有新发现
- Sql Server存储过程的调试
- sqlite数据类型对应的 .NET 数据类型名称
- 窗体继承,然后实现按钮点击事件的重写
- php仿javascript的escape和unescape用于简单网页加密
- C/S模式的程序,用户信息应该保存在哪里呢?
- ASP.NET(C#)返回上一页(后退)代码