java mysql封装_Java之对于jdbc对数据库的封装

packagecom.myweb.utils;importjava.io.IOException;importjava.io.InputStream;importjava.lang.reflect.Field;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.ResultSetMetaData;importjava.sql.SQLException;importjava.sql.Statement;importjava.sql.Types;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importjava.util.Properties;public classDBManager {/***@paramargs*/

staticString driver;staticString url;staticString username;staticString password;privateConnection connection;privatePreparedStatement pstmt;privateResultSet resultSet;publicDBManager() {

InputStream in= DBManager.class.getClassLoader().getResourceAsStream("db.properties");

Properties pro= newProperties();try{

pro.load(in);

}catch(IOException e) {

e.printStackTrace();

}

driver= pro.getProperty("driver");

url= pro.getProperty("url");

username= pro.getProperty("username");

password= pro.getProperty("password");try{

Class.forName(driver);

}catch(Exception e) {

}

}/*** 获得数据库的连接

*

*@return*@throwsClassNotFoundException*/

publicConnection getConnection() {try{

Class.forName(driver);

connection=DriverManager.getConnection(url, username, password);

}catch(SQLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(Exception e) {

System.out.println("fail to connect database");

}returnconnection;

}/*** 获得最大ID

*

*@paramtableName

*@return*@throwsSQLException*/

public intgetMaxId(String tableName) {

Statement state= null;

ResultSet rs= null;int maxId = 0;try{

state=connection.createStatement();

String sql= "select max(id) maxId from " +tableName;

rs=state.executeQuery(sql);//从resultset对象中将数据取出

if(rs.next()) {

maxId= rs.getInt("maxId");

}

}catch(Exception ex) {//TODO Auto-generated catch block

ex.printStackTrace();

}return ++maxId;

}/*** 增加、删除、改

*

*@paramsql

*@paramparams

*@return*@throwsSQLException*/

public boolean updateByPreparedStatement(String sql, Listparams)throwsSQLException {boolean flag = false;int result = -1;

pstmt=connection.prepareStatement(sql);int index = 1;if (params != null && !params.isEmpty()) {for (int i = 0; i < params.size(); i++) {

pstmt.setObject(index++, params.get(i));

}

}

result=pstmt.executeUpdate();

flag= result > 0 ? true : false;returnflag;

}/*** 查询单条记录

*

*@paramsql

*@paramparams

*@return*@throwsSQLException*/

public Map findSimpleResult(String sql, Listparams)throwsSQLException {

Map map = new HashMap();int index = 1;

pstmt=connection.prepareStatement(sql);if (params != null && !params.isEmpty()) {for (int i = 0; i < params.size(); i++) {

pstmt.setObject(index++, params.get(i));

}

}

resultSet= pstmt.executeQuery();//返回查询结果

ResultSetMetaData metaData =resultSet.getMetaData();int col_len =metaData.getColumnCount();while(resultSet.next()) {for (int i = 0; i < col_len; i++) {

String cols_name= metaData.getColumnName(i + 1);

Object cols_value=resultSet.getObject(cols_name);if (cols_value == null) {

cols_value= "";

}

map.put(cols_name, cols_value);

}

}returnmap;

}/*** 查询多条记录

*

*@paramsql

*@paramparams

*@return*@throwsSQLException*/

public List>findModeResult(String sql,

List params) throwsSQLException {

List> list = new ArrayList>();int index = 1;

pstmt=connection.prepareStatement(sql);if (params != null && !params.isEmpty()) {for (int i = 0; i < params.size(); i++) {

pstmt.setObject(index++, params.get(i));

}

}

resultSet=pstmt.executeQuery();

ResultSetMetaData metaData=resultSet.getMetaData();int cols_len =metaData.getColumnCount();while(resultSet.next()) {

Map map = new HashMap();for (int i = 0; i < cols_len; i++) {

String cols_name= metaData.getColumnName(i + 1);

Object cols_value=resultSet.getObject(cols_name);if (cols_value == null) {

cols_value= "";

}

map.put(cols_name, cols_value);

}

list.add(map);

}returnlist;

}/*** 通过反射机制查询单条记录

*

*@paramsql

*@paramparams

*@paramcls

*@return*@throwsException*/

public T findSimpleRefResult(String sql, Listparams,

Class cls) throwsException {

T resultObject= null;int index = 1;

pstmt=connection.prepareStatement(sql);if (params != null && !params.isEmpty()) {for (int i = 0; i < params.size(); i++) {

pstmt.setObject(index++, params.get(i));

}

}

resultSet=pstmt.executeQuery();

ResultSetMetaData metaData=resultSet.getMetaData();int cols_len =metaData.getColumnCount();while(resultSet.next()) {//通过反射机制创建一个实例

resultObject =cls.newInstance();for (int i = 0; i < cols_len; i++) {

String cols_name= metaData.getColumnName(i + 1);

Object cols_value=resultSet.getObject(cols_name);int type = metaData.getColumnType(i + 1);if (cols_value == null) {if (type ==Types.INTEGER) {

cols_value= 0;

}else{

cols_value= "";

}

}

Field field=cls.getDeclaredField(cols_name.toLowerCase());

field.setAccessible(true); //打开javabean的访问权限

if (type ==Types.TIMESTAMP) {

field.set(resultObject, String.valueOf(cols_value));

}else{

field.set(resultObject, cols_value);

}

}

}returnresultObject;

}/*** 通过反射机制查询多条记录

*

*@paramsql

*@paramparams

*@paramcls

*@return*@throwsException*/

public List findMoreRefResult(String sql, Listparams,

Class cls) throwsException {

List list = new ArrayList();int index = 1;

pstmt=connection.prepareStatement(sql);if (params != null && !params.isEmpty()) {for (int i = 0; i < params.size(); i++) {

pstmt.setObject(index++, params.get(i));

}

}

resultSet=pstmt.executeQuery();

ResultSetMetaData metaData=resultSet.getMetaData();int cols_len =metaData.getColumnCount();while(resultSet.next()) {//通过反射机制创建一个实例

T resultObject =cls.newInstance();for (int i = 0; i < cols_len; i++) {

String cols_name= metaData.getColumnName(i + 1);

Object cols_value=resultSet.getObject(cols_name);if (cols_value == null) {

cols_value= "";

}

Field field=cls.getDeclaredField(cols_name);

field.setAccessible(true); //打开javabean的访问权限

field.set(resultObject, cols_value);

}

list.add(resultObject);

}returnlist;

}/*** 释放数据库连接*/

public voidreleaseConn() {if (resultSet != null) {try{

resultSet.close();

}catch(SQLException e) {

e.printStackTrace();

}

}

}/***@paramargs

*@throwsClassNotFoundException*/

public static void main(String[] args) throwsSQLException, ClassNotFoundException {/*DBManager db = new DBManager();

Connection connection2 = db.getConnection();

System.out.println(connection2);*/

//TODO Auto-generated method stubs//JdbcUtils jdbcUtils = new JdbcUtils();//jdbcUtils.getConnection();

/******************* 增 *********************/

/** String sql =

* "insert into userinfo (username, pswd) values (?, ?), (?, ?), (?, ?)"

* ; List params = new ArrayList(); params.add("小明");

* params.add("123xiaoming"); params.add("张三"); params.add("zhangsan");

* params.add("李四"); params.add("lisi000"); try { boolean flag =

* jdbcUtils.updateByPreparedStatement(sql, params);

* System.out.println(flag); } catch (SQLException e) { // TODO

* Auto-generated catch block e.printStackTrace(); }*/

/******************* 删 *********************/

//删除名字为张三的记录

/** String sql = "delete from userinfo where username = ?"; List

* params = new ArrayList(); params.add("小明"); boolean flag =

* jdbcUtils.updateByPreparedStatement(sql, params);*/

/******************* 改 *********************/

//将名字为李四的密码改了

/** String sql = "update userinfo set pswd = ? where username = ? ";

* List params = new ArrayList();

* params.add("lisi88888"); params.add("李四"); boolean flag =

* jdbcUtils.updateByPreparedStatement(sql, params);

* System.out.println(flag);*/

/******************* 查 *********************/

//不利用反射查询多个记录

/** String sql2 = "select * from userinfo "; List>

* list = jdbcUtils.findModeResult(sql2, null);

* System.out.println(list);*/

//利用反射查询 单条记录

/** String sql = "select * from userinfo where username = ? ";

* List params = new ArrayList(); params.add("李四");

* UserInfo userInfo; try { userInfo =

* jdbcUtils.findSimpleRefResult(sql, params, UserInfo.class);

* System.out.print(userInfo); } catch (Exception e) { // TODO

* Auto-generated catch block e.printStackTrace(); } Class clcs =

* UserInfo.class; try { Object obj = clcs.newInstance(); Method f =

* clcs.getDeclaredMethod("setUsername", String.class); f.invoke(obj,

* "yan123"); Method f2 = clcs.getDeclaredMethod("getUsername", null);

* Object name = f2.invoke(obj, null); System.out.println("反射得到的名字 = " +

* name);

*

* } catch (InstantiationException e) { // TODO Auto-generated catch

* block e.printStackTrace(); } catch (IllegalAccessException e) { //

* TODO Auto-generated catch block e.printStackTrace(); } catch

* (NoSuchMethodException e) { // TODO Auto-generated catch block

* e.printStackTrace(); } catch (SecurityException e) { // TODO

* Auto-generated catch block e.printStackTrace(); } catch

* (IllegalArgumentException e) { // TODO Auto-generated catch block

* e.printStackTrace(); } catch (InvocationTargetException e) { // TODO

* Auto-generated catch block e.printStackTrace(); }*/}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值