有关数据库连接的类

来源:互联网 发布:手机机器人对话软件 编辑:程序博客网 时间:2024/06/05 03:28

package com.mstanford.dao;

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

public class DBManager {
 
 private static final String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
 private static final String url="jdbc:sqlserver://localhost:1433;databasename=productDB";
 private static final String user="sa";
 private static final String pwd="sa";
 private static Connection con=null;
 
 //连接数据库的方法
 public static Connection getCon(){
  try {
   Class.forName(driver);
   con=DriverManager.getConnection(url,user,pwd);
   
  } catch (Exception e) {
   e.printStackTrace();
  }
  return con;
 }
 //关闭数据库的链接
 public static void closeCon(Connection con){
  try {
   if(con!=null){
    con.close();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 //关闭数据库的添加和修改等信息
 public static void closeStatement(PreparedStatement pst){
  try {
   if(pst!=null){
    pst.close();
    pst=null;
   }
  } catch (Exception e) {
   // TODO: handle exception
  }
 }
 //关闭数据库的结果的链接
 public static void closeResult(ResultSet rst){
  try {
   if(rst!=null){
    rst.close();
    rst=null;
   }
  } catch (Exception e) {
   // TODO: handle exception
  }
 }
 public static void main(String[] args) {
  System.out.println(DBManager.getCon());
 }
 }