SqlServer数据库连接公共类--BaseDao

来源:互联网 发布:云烟淘宝客助手多少钱 编辑:程序博客网 时间:2024/05/10 10:51

import java.sql.Connection;       / /导入连接对象必备包
import java.sql.DriverManager;   //导入sqlServer数据库驱动必备包
import java.sql.PreparedStatement;   //导入sql语句预编译对象必备包
import java.sql.ResultSet;  //导入结果集对象必备包
public class BaseDao {

protected Connection con;    / /创建连接对象
 protected PreparedStatement psta;  //创建sql语句预编译对象
 protected ResultSet rst;   //创建果集对象
 
/**获得数据库连接对象*/
 protected Connection getCon(){
  //加载驱动
  try {   
   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
   //获得连接
   String url = "jdbc:sqlserver://localhost:1433;databaseName=数据库名";
   con = DriverManager.getConnection(url,"sa","t密码");
  } catch (Exception e) {
   e.printStackTrace();
  }   
  return con;   //返回对象
 }  


 /**关闭连接*/
 protected void closeAll(){
  try {
   if(rst != null){
    rst.close();
   }
   if(psta != null){
    psta.close();
   }
   if(con != null && !con.isClosed()){
    con.close();
   }
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 

/**测试连接是否成功*/
 public static void main(String[] args) {
  BaseDao bd = new BaseDao();
  System.out.println(bd.getCon());
 }
}