问题描述:
下面是有关连接SqlServer2008R2和MySql数据库的封装类
1 package com.test;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5
6 public class DataBaseConn {
7
8 private String databaseName = "";//数据名称
9 private String useName = "";//用户登入名
10 private String password ="";//登入密码
11
12 public DataBaseConn(){
13 this.databaseName = "INTRUST";
14 this.useName = "sa";
15 this.password = "000000";
16 }
17
18 public DataBaseConn(String databaseName, String useName, String password){
19 this.databaseName = databaseName;
20 this.useName = useName;
21 this.password = password;
22 }
23
24 public Connection con = null;
25
26 private String MYSQLDRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
27 private String MYSQLURL = "jdbc:mysql://localhost:3306/" + databaseName + "?use" + useName + "&password" + password + "&useUnicode=true&characterEncoding=gb2312";
28 //SQLsServer驱动
29 private String MSSQLDRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
30 private String MSSQLURL = "jdbc:sqlserver://localhost:1433;DatabaseName=INTRUST";
31
32 public void createMysqlConn(){
33 con = null;
34 try{
35 Class.forName(MYSQLDRIVER).newInstance();
36 con = DriverManager.getConnection(MYSQLURL);
37 }catch(Exception e){
38 e.printStackTrace();
39 }
40 }
41 //SQLsServer驱动
42 public void createMssqlConn(){
43 con = null;
44 try{
45 Class.forName(MSSQLDRIVER).newInstance();
46 con = DriverManager.getConnection(MSSQLURL, "sa", "000000");
47 }catch(Exception e){
48 e.printStackTrace();
49 }
50 }
51
52 public Connection getMysqlConn(){
53 createMysqlConn();
54 return con;
55 }
56
57 public Connection getMssqlConn(){
58 createMssqlConn();
59 return con;
60 }
61
62 public void closeCon(){
63 if(con != null){
64 try {
65 con.close();
66 con = null;
67 } catch (Exception e) {
68 // TODO Auto-generated catch block
69 e.printStackTrace();
70 }
71 }
72 }
73
74 }