您的位置:首页 > 数据库 > MySQL

与Mysql进行连接JDBC的Dao工厂类

2012-10-15 01:01 302 查看
/*

* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package util;

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

/**
*
* @author eblink
*/
public class Factory {
// 加载驱动,创建Connection对象,建立数据库连接
public static Connection getConnection(){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/test";//test为数据库
String user="root";
String password="123456";
Connection conn=null;
try{
//加载MySQL的JDBC驱动
Class.forName(driver);
//建立数据库连接
conn=DriverManager.getConnection(url,user,password);
}catch(Exception e){
e.printStackTrace();
System.out.println("与MySQL数据库连接失败");
}
return conn;
}

// 关闭相关连接,释放资源
public static void closeAll(Connection conn,Statement st,ResultSet rs){
try{
if(rs!=null){
rs.close();
}
if(st!=null){
st.close();
}
if(conn!=null){
conn.close();
}
}catch(Exception e){
e.printStackTrace();
System.out.println("数据库相关资源关闭失败!");
}
}
}
本文出自 “黄河之水” 博客,请务必保留此出处http://eblink.blog.51cto.com/5088779/1025610
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: