您的位置:首页 > 编程语言 > Java开发

java连接数据库工具类写法

2015-05-25 22:54 344 查看
创建一个dao.imp包,此类涉及到一般数据库的基本操作,可以当工具类用
package dao.imp;

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

public class DatabaseDAO {
private Connection conn=null;
/**
* @return 数据库连接对象
* @throws ClassNotFoundException
* @throws SQLException
*/
public Connection getConnection()throws ClassNotFoundException,
SQLException{
Connection conn=null;
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");

//初始化数据库连接字符串并指定字符串编码集
String url="jdbc:mysql://localhost:3306/society?useUnicode=true&" +
"characterEncoding=utf-8";
//声明并初始化数据库用户名和密码
String user="root";
String password="m1234";

//连接数据库并验证数据
conn=DriverManager.getConnection(url, user, password);
System.out.println("Connection created!");
return conn;
}
/**
* 关闭类中的连接对象
* @throws SQLException
*/
public void releaseConnection() throws SQLException{
this.conn.close();
this.conn=null;
}
/**
* 执行一个sQL的查询语句,并返回一个结果集
* @param SQL查询语句
* @return 数据库查询结果集
* @throws SQlException
* @throws ClassNotFoundException
*/
public ResultSet getResultSet(String querySQL)throws SQLException,
ClassNotFoundException{
if(conn==null)
{
this.conn=getConnection();
}
Statement stm=conn.createStatement();
//执行查询语句,并返回查询结果集
ResultSet thisRST=stm.executeQuery(querySQL);
return thisRST;

}
/**
* 直接执行一条对数据库修改(包括增删改)的SQL语句
* @param SQL语句
* @throws SQLException
* @throws ClassNotFoundException
*/
public void executeSQL(String SQL)throws SQLException,
ClassNotFoundException{
if(conn==null)
{
this.conn=getConnection();
}
Statement stm=conn.createStatement();
//执行给定的SQL语句
stm.execute(SQL);
//关闭连接对象
this.conn.close();
this.conn=null;
}
/**
* 测试主函数
* @param args
* @throws SQLException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//声明连接类对象
DatabaseDAO dd=new DatabaseDAO();
if(dd.getConnection()!=null)
{
System.out.println("数据库连接成功!");
}
else
System.out.println("连接失败");
}

}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 数据库