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连接MySQL 和 MSSQL数据库写法
- java中常用的工具类(三)连接数据库的综合类,DES加密和解密,Base64,ExcelUtil工具类,
- Java连接各数据库写法
- java中配置文件数据库连接写法
- java 连接数据库通用工具类
- java连接数据库进行增添数据的不同写法
- java实现数据库连接的工具类
- JavaWeb之JDBC(二)采用读取配置文件方式编写JDBC的工具类,获取数据库的连接
- Java常用工具类封装——连接数据库的工具类
- java连接数据库的工具类
- java连接数据库的工具类
- 数据库连接工具类 数据库连接工具类——仅仅获得连接对象 ConnDB.java
- Java开发数据库连接JDBC工具类
- java 连接各种数据库写法
- 数据库连接工具类——包含取得连接和关闭资源 ConnUtil.java
- java连接各种数据库的配置文件写法
- java连接几种常见的数据库 字符串 写法
- java连接各种数据库的写法
- java连接各种数据库的写法
- Java使用JDBC连接数据库完整的工具类实例