[java]代码库
//单态设计模式的JDBC
package com.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* JDBC
* @author Administrator
*
*/
public class DbUtil {
private static DbUtil db=new DbUtil();
private final String URL="jdbc:mysql://localhost:3306/Librarymanagement";
private final String NAME="root";
private final String PASSWORD="123456";
/**
* 注册驱动
*/
private DbUtil(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("注册驱动失败");
}
}
/**
* 得到db链接数据库
* @return
*/
public static DbUtil getDb() {
return db;
}
/**
* 链接数据库
* @return
*/
public Connection getConn(){
Connection con=null;
try {
con=DriverManager.getConnection(URL,NAME,PASSWORD);
System.out.println("ok-ok-lianjie");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//链接数据库
return con;
}
/**
* 关闭数据库
* @param obj
*/
public void closeDb(Object obj){
try {
if(obj instanceof ResultSet){
ResultSet th=(ResultSet)obj;
th.close();
}else if(obj instanceof Statement){
Statement st=(Statement)obj;
st.close();
}else if(obj instanceof Connection){
Connection con=(Connection)obj;
con.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("关闭失败");
}
}
}