数据库连接代码模板

来源:互联网 发布:java小游戏卡丁车源码 编辑:程序博客网 时间:2024/06/07 05:34

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库连接类
 */

public class BaseDao {

 //2005的驱动连接
 //com.microsoft.sqlserver.jdbc.SQLServerDriver
 //jdbc:sqlserver://localhost:1433;databasename=company
 
 //  2000的驱动连接
 //com.microsoft.jdbc.sqlserver.SQLServerDriver
 //jdbc:microsoft:sqlserver://localhost:1433;databasename=company
 
 //数据库驱动
 private final static String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
 // URL
 private final static String URL="jdbc:sqlserver://localhost:1433;DataBaseName=databaseName";
 //数据库用户名
 private final static String DBNAME="sa";
 //数据库密码
 private final static String DBPASS="sa"; 
 
 /**
  * 得到数据库连接
  * @return 数据库连接
  * @throws ClassNotFoundException
  * @throws SQLException
  */
 public static Connection getConn() throws ClassNotFoundException,SQLException{
  Class.forName(DRIVER); //注册驱动
  Connection conn=DriverManager.getConnection(URL,DBNAME,DBPASS);
  return conn;
 }
 
 /**
  * 关闭数据库相关连接
  * @param conn
  * @param pstmt
  * @param rs
  */
 public static void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs){
  /*如果rs不空,关闭rs*/
  if(rs!=null){
   try{
    rs.close();
   }catch(SQLException e){
    e.printStackTrace();
   }
  }
  
  /*如果pstmt不空,关闭pstmt*/
  if(pstmt!=null){
   try{
    pstmt.close();
   }catch(SQLException e){
    e.printStackTrace();
   }
  }
  
  /*如果conn不空,关闭conn*/
  if(conn!=null){
   try{
    conn.close();
   }catch(SQLException e){
    e.printStackTrace();
   }
  }
 }
 /**
  * 执行SQL语句,可以进行增、删、改、的操作,不能执行查询
  * @param preparedSql 预编译的 SQL 语句
  * @param param 预编译的SQL语句中的'?'参数的字符串数组
  * @return 影响的条数
  */
 public static int executeSQL(String preparedSql,String[] param){
  Connection conn=null;
  PreparedStatement pstmt=null;
  int num=0;
  /*处理SQL,执行SQL*/
  try{
   conn=getConn();  //得到数据库连接
   pstmt=conn.prepareStatement(preparedSql);
   if(param!=null){
    for(int i=0;i<param.length;i++){
     pstmt.setString(i+1, param[i]); //设置参数
    }
   }
   num=pstmt.executeUpdate(); //执行SQL语句
  }catch(ClassNotFoundException e){
   e.printStackTrace(); //处理ClassNotFountException异常
  }catch(SQLException e){
   e.printStackTrace(); //处理SQLException异常
  }finally{
   closeAll(conn,pstmt,null); //释放资源
  }
  return num;
 }  
}

原创粉丝点击