连接MySql数据库
CT-Manager测试管理系统采用的是MySql5.1进行开发的!这个是连接Mysql的数据库脚本!希望对大家有利!
package com.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DBConn {
public static Connection conn=null;
public ResultSet rs=null;
public Statement st=null;
private static String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3307/ct_manager";
private static String username="root";
private static String password="root";
private static DBConn dbConn=null;
//单例模式
private DBConn(){}
public static DBConn getDBConn(){
if(dbConn==null){
dbConn=new DBConn();
}
return dbConn;
}
//获取数据库连接
public Connection getConnection(){
try {
Class.forName(driver);
conn=DriverManager.getConnection(url,username,password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//三个参数的关闭方法
public static void close(Statement st,ResultSet rs,Connection conn){
try {
if(st!=null){st.close();}
if(rs!=null){rs.close();}
if(conn!=null){conn.close();}
} catch (Exception e) {
e.printStackTrace();
}
}
//语句的关闭
public static void close(Statement st){
try {
if(st!=null){st.close();}
} catch (Exception e) {
e.printStackTrace();
}
}
//结果集的关闭
public static void close(ResultSet rs){
try {
if(rs!=null){rs.close();}
} catch (Exception e) {
e.printStackTrace();
}
}
//连接的关闭
public static void close(Connection conn){
try {
if(conn!=null){conn.close();}
} catch (Exception e) {
e.printStackTrace();
}
}
//测试数据库是否连接成功
public static void main(String a[]){
DBConn dbConn=DBConn.getDBConn();
Connection conn=null;
conn=dbConn.getConnection();
if(conn!=null){
System.out.println("success!!");
}
dbConn.close(conn);
}
}
每天一点点希望对大家有利!