java连接数据库工具类写法

创建一个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("连接失败");
	}

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值