与Sql连接的javabean

来源:互联网 发布:淘宝发货不需要物流 编辑:程序博客网 时间:2024/05/01 10:52
package com.bwm.dbc;
import java.sql.*;
public class Conn{
private static Connection con;
private Statement stmt;
private ResultSet rs;
private static final string drivenname="com.microsoft.jdbc.sqlserver.SQLServerDriver";
//数据库连接URL
private static final String url="jdbc:microsoft:sqlserver://127.0.0.1:1433;Database
Name=pubs;user=sa;password=;"123";
/*获取数据库的连接*/
public static synchronized Connection getCOn()throws Exception{
  try{
//加载驱动程序
     Class.forName(drivename);
//获取数据库连接
     con=DriveManager.getConnection(url);
     return con;
    }catch(SQLException e){
         System.err.println(e.getMessage());
         throw e;
    }  
}
/*获取Statement只能用于查询的语句*/ 
public Statement getStmtread(){
         try{
                con=getCon();
               //创建Statement对象
           stmt=con.createStatement(resultSet.TYPE_SCROLL_INSENSITIVE,
                                    ResultSet.CONCUR_READ_ONLY);
            return null;
           }catch(Exception e){
                           System.err.println(e.getMessage());
                           e.printStackTrace();
                    }
             return null;
         }
/* 获取result*/
public ResultSet getRs(string sql) {
         try{
           stmt=getStmtread();
//创建ResultSet对象
              rs=stmt.excuteQuery(sql);
              return rs;
            }catch(Exception e){
                           System.err.println(e.getMessage());
                           e.printStackTrace();
                    }
             return null;
         }
/*获取Statement用于删除,更新,和添加的SQL语句*/
      
     public Statement getStmt(){
        try{
             con=getCon();
             stmt=con.createStatement();
             return  stmt;
                }catch(Exception e){
                           System.err.println(e.getMessage());
                           e.printStackTrace();
                    }
             return null;
         }  
/*关闭数据库的连接*/
       public synchronized void close(){
          try{
               if(rs!=null){
                    rs.close();
                    rs=null;
                   }    
                  }catch(Exception e){
                           System.err.println(e.getMessage());
                           e.printStackTrace();
                    }
          
             try{
                  if(stmt!=null){
                   stmt.close();
                   stmt=null;
                        }
                  }catch(Exception e){
                           System.err.println(e.getMessage());
                           e.printStackTrace();
                    }
          try{
               if(con!=null){
                    con.close();
                    con=null;
                    }
                  }catch(Exception e){
                           System.err.println(e.getMessage());
                           e.printStackTrace();
                    }
             }
         }
 
原创粉丝点击