c mysql 工具类_Jave工具——servlet+jsp编程中mysql数据库连接及操作通用工具类
該工具類是在JavaWeb中連接mysql所用到的通用工具類
該類用于Java+Servlet的編程中,方便數(shù)據(jù)庫的操作,連接,獲取其列表值。下面是這個(gè)數(shù)據(jù)庫操作類的通用方法,基本上能夠用于類里面只含有簡(jiǎn)單數(shù)據(jù)的類,例如類是Date,int,double,String等數(shù)據(jù)庫里面包含的類型。
這個(gè)并不是一個(gè)模板,而是一個(gè)工具類,也就是說,符合只有簡(jiǎn)單數(shù)據(jù)的類可以直接調(diào)用以下提供的功能就能操作數(shù)據(jù)庫,返回類的List的值。
之前在進(jìn)行編程的時(shí)候發(fā)現(xiàn)在操作數(shù)據(jù)庫的過程中特別麻煩,每次重新寫一個(gè)新類要存儲(chǔ)到數(shù)據(jù)庫的話,總是要在service寫新的方法才能適應(yīng)相應(yīng)的操作,但是我覺得這些方法大都大同小異,似乎沒有必要每次都為一個(gè)類寫一個(gè)方法適應(yīng)一個(gè)新的類。所以寫這個(gè)通用數(shù)據(jù)庫操作的類的想法就產(chǎn)生了。
首先,該工具主要是對(duì)數(shù)據(jù)庫進(jìn)行操作,所以首先要對(duì)數(shù)據(jù)庫進(jìn)行連接,下面是實(shí)現(xiàn)對(duì)數(shù)據(jù)庫連接的一個(gè)DBUtil.java文件,實(shí)現(xiàn)了對(duì)數(shù)據(jù)庫的連接
packagecom.hjf.util;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;/*** 數(shù)據(jù)庫連接工具
*@authorHDQ
**/
public classDBUtil {public static String db_url = "jdbc:mysql://localhost:3306/數(shù)據(jù)庫名";public static String db_user = "數(shù)據(jù)庫用戶名";public static String db_pass = "數(shù)據(jù)庫密碼";public staticConnection getConn () {
Connection conn= null;try{
Class.forName("com.mysql.jdbc.Driver");//加載驅(qū)動(dòng)
conn =DriverManager.getConnection(db_url, db_user, db_pass);
}catch(Exception e) {
e.printStackTrace();
}returnconn;
}/*** 關(guān)閉連接
*@paramstate
*@paramconn*/
public static voidclose (Statement state, Connection conn) {if (state != null) {try{
state.close();
}catch(SQLException e) {
e.printStackTrace();
}
}if (conn != null) {try{
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}public static voidclose (ResultSet rs, Statement state, Connection conn) {if (rs != null) {try{
rs.close();
}catch(SQLException e) {
e.printStackTrace();
}
}if (state != null) {try{
state.close();
}catch(SQLException e) {
e.printStackTrace();
}
}if (conn != null) {try{
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}public static void main(String[] args) throwsSQLException {
Connection conn=getConn();
PreparedStatement pstmt= null;
ResultSet rs= null;
String sql="select * from course";
pstmt=conn.prepareStatement(sql);
rs=pstmt.executeQuery();if(rs.next()){
System.out.println("空");
}else{
System.out.println("不空");
}
}
}
然后在對(duì)數(shù)據(jù)庫連接完成之后,接著就是對(duì)數(shù)據(jù)庫進(jìn)行操作的一個(gè)類了,這個(gè)類位于dao層
這個(gè)ClassDao.java類可以根據(jù)傳遞進(jìn)來的參數(shù)返回相應(yīng)類型的類的List,其實(shí)現(xiàn)的原理是利用Field 反射其值到對(duì)應(yīng)的類里面,所以在使用的時(shí)候帶有返回List的功能的時(shí)候,其數(shù)據(jù)庫里面的數(shù)據(jù)項(xiàng)名稱和類里面定義的變量的名稱需要保持一致,才能保證其值被正確反射到類里面,反射機(jī)制所以返回的類的List都已經(jīng)被賦予相應(yīng)的值,可以直接被使用
相應(yīng)的操作方法用法會(huì)在本文的最后給出,ClassDao.java是一個(gè)通用操作類,實(shí)現(xiàn)了對(duì)數(shù)據(jù)庫操作
packagecom.hjf.dao;importjava.lang.reflect.Field;importjava.lang.reflect.Modifier;importjava.sql.Connection;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importjava.util.ArrayList;importjava.util.List;importcom.hjf.util.DBUtil;/*** 通用類Dao
* Dao層操作數(shù)據(jù)
*@authorHDQ
**/
public classClassDao {/*** 添加*@return
*/
public booleanadd(String table,String []strList,String []strList1) {if(strList.length==0)return false;
String sql= "insert into "+table+"(";for(int i=0;i
{if(i!=strList.length-1)
sql+=strList[i]+",";else sql+=strList[i]+")";
}
sql+=" values('";for(int i=0;i
{if(i!=strList1.length-1)
sql+=strList1[i]+"','";else sql+=strList1[i]+"')";
}//創(chuàng)建數(shù)據(jù)庫鏈接
Connection conn =DBUtil.getConn();
Statement state= null;boolean f = false;int a = 0;try{
state=conn.createStatement();
a=state.executeUpdate(sql);
}catch(Exception e) {
e.printStackTrace();
}finally{//關(guān)閉連接
DBUtil.close(state, conn);
}if (a > 0) {
f= true;
}returnf;
}/*** 刪除
**@return
*/
public booleandelete (String table,String zhixing,String biaoshi) {boolean f = false;
String sql= "delete from "+table+" where "+zhixing+"='" + biaoshi + "'";
Connection conn=DBUtil.getConn();
Statement state= null;int a = 0;try{
state=conn.createStatement();
a=state.executeUpdate(sql);
}catch(SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(state, conn);
}if (a > 0) {
f= true;
}returnf;
}/*** 修改*/
public booleanupdate(String table,String []strlist,String []strlist1,String qian,String hou) {
String sql= "update "+table+" set ";for(int i=0;i
{if(i!=strlist.length-1)
sql+=strlist[i]+"='" + strlist1[i] + "',";else sql+=strlist[i]+"='" + strlist1[i] + "' where "+qian+"='" + hou + "'";
}
Connection conn=DBUtil.getConn();
Statement state= null;boolean f = false;int a = 0;try{
state=conn.createStatement();
a=state.executeUpdate(sql);
}catch(SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(state, conn);
}if (a > 0) {
f= true;
}returnf;
}/*** 驗(yàn)證通用類名稱是否唯一
* true --- 不唯一
*@return
*/
public booleanname(String table,String zhi,String weiyi) {boolean flag = false;
String sql= "select "+zhi+" from "+table+" where "+zhi+" = '" + weiyi + "'";
Connection conn=DBUtil.getConn();
Statement state= null;
ResultSet rs= null;try{
state=conn.createStatement();
rs=state.executeQuery(sql);while(rs.next()) {
flag= true;
}
}catch(SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(rs, state, conn);
}returnflag;
}/*** 查找*@return*@throwsIllegalAccessException
*@throwsInstantiationException*/@SuppressWarnings("deprecation")public List search(String table,String []strList,String []strList1,Class clazz) throwsInstantiationException, IllegalAccessException {
String sql= "select * from "+table;int i=0,k=0;for(String it:strList1)
{if(it!=null&&!it.equals(""))
{if(k==0)
sql+=" where "+ strList[i]+" like '%" + it + "%'";else sql +=" and "+ strList[i]+" like '%" + it + "%'";++k;
}++i;
}
List list = new ArrayList<>();
Connection conn=DBUtil.getConn();
Statement state= null;
ResultSet rs= null;try{
state=conn.createStatement();
rs=state.executeQuery(sql);
T bean= null;while(rs.next()) {
bean=clazz.newInstance();for(String it:strList)
{
Field fs=getDeclaredField(bean, it);if(fs==null){throw new IllegalArgumentException("Could not find field["+it+"] on target ["+bean+"]");
}
makeAccessiable(fs);try{
fs.set(bean, rs.getObject(it));
}catch(IllegalAccessException e){
System.out.println("不可能拋出的異常");
}
}
list.add(bean);
}
}catch(SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(rs, state, conn);
}returnlist;
}/*** 由時(shí)間和條件查找*@return*@throwsIllegalAccessException
*@throwsInstantiationException*/@SuppressWarnings("deprecation")public List searchByTime(String table,String []strList,String []strList1,String biaoshi,String qian,String hou,Class clazz) throwsInstantiationException, IllegalAccessException {
String sql= "select * from "+table+" where ";int i=0,k=0;for(String it:strList1)
{if(it!=null&&!it.equals(""))
{
sql+= strList[i]+" like '%" + it + "%'";++k;
}++i;
}if(qian!=null&&!qian.equals(""))
{if(k>0)
sql+=" and "+biaoshi+" Between '"+qian+"' AND '"+hou+"'";else sql+=biaoshi+" Between '"+qian+"' AND '"+hou+"'";
}//and shijian Between '"+request.getParameter("shijian1")+"' AND '"+request.getParameter("shijian2")+"'"//查詢的時(shí)間格式例如:2015-10-27 24:00:0(假如為DateTime的話,Date只需要年-月-日)
List list = new ArrayList<>();
Connection conn=DBUtil.getConn();
Statement state= null;
ResultSet rs= null;try{
state=conn.createStatement();
rs=state.executeQuery(sql);
T bean= null;while(rs.next()) {
bean=clazz.newInstance();for(String it:strList)
{
Field fs=getDeclaredField(bean, it);if(fs==null){throw new IllegalArgumentException("Could not find field["+it+"] on target ["+bean+"]");
}
makeAccessiable(fs);try{
fs.set(bean, rs.getObject(it));
}catch(IllegalAccessException e){
System.out.println("不可能拋出的異常");
}
}
list.add(bean);
}
}catch(SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(rs, state, conn);
}returnlist;
}/*** 創(chuàng)建數(shù)據(jù)庫*@return*@throwsClassNotFoundException
*@throwsIllegalAccessException
*@throwsInstantiationException*/
public boolean createTable(String table,String []info,String []type,int[]size)
{
String sql= "CREATE TABLE "+table+"(";
String lei[]=new String[] {"char","varchar"};int i=0;for(String it:info)
{if(!it.equals(""))
{boolean g_trit=false;for(String sit:lei)
{if(type[i].toLowerCase().contains(sit.toLowerCase()))
{
g_trit=true;
}
}if(g_trit)
sql+= it+" "+type[i]+"("+size[i]+")";else sql += it+" "+type[i];
}if(i!=info.length-1)
sql+=",";++i;
}
sql+=")";//and shijian Between '"+request.getParameter("shijian1")+"' AND '"+request.getParameter("shijian2")+"'"//查詢的時(shí)間格式例如:2015-10-27 24:00:0
Connection conn =DBUtil.getConn();
Statement state= null;
ResultSet rs= null;int a=0;boolean f=false;try{
state=conn.createStatement();
a=state.executeUpdate(sql);
}catch(SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(rs, state, conn);
}if(a>0)
f=true;returnf;
}/*** 全部數(shù)據(jù)*@return*@throwsClassNotFoundException
*@throwsIllegalAccessException
*@throwsInstantiationException*/@SuppressWarnings("deprecation")public List list(String table,String []strList,Class clazz) throwsClassNotFoundException, InstantiationException, IllegalAccessException {
String sql= "select * from "+table;
List list = new ArrayList<>();
Connection conn=DBUtil.getConn();
Statement state= null;
ResultSet rs= null;try{
state=conn.createStatement();
rs=state.executeQuery(sql);
T bean= null;while(rs.next()) {
bean=clazz.newInstance();for(String it:strList)
{
Field fs=getDeclaredField(bean, it);if(fs==null){throw new IllegalArgumentException("Could not find field["+it+"] on target ["+bean+"]");
}
makeAccessiable(fs);try{
fs.set(bean, rs.getObject(it));
}catch(IllegalAccessException e){
System.out.println("不可能拋出的異常");
}
}
list.add(bean);
}
}catch(SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(rs, state, conn);
}returnlist;
}//獲取field屬性,屬性有可能在父類中繼承
public staticField getDeclaredField(Object obj,String fieldName){for (Class> clazz=obj.getClass(); clazz!=Object.class; clazz=clazz.getSuperclass()){try{returnclazz.getDeclaredField(fieldName);
}catch(Exception e){
}
}return null;
}//判斷field的修飾符是否是public,并據(jù)此改變field的訪問權(quán)限
public static voidmakeAccessiable(Field field){if(!Modifier.isPublic(field.getModifiers())){
field.setAccessible(true);
}
}
}
在dao層里面的方法應(yīng)該是為了安全性考慮吧,還要有一個(gè)sevice類來調(diào)用dao層里面的方法,就相當(dāng)一個(gè)中介一樣吧,也就是一個(gè)提供dao層里面接口的一個(gè)類,以下是位于service層的service.java,實(shí)現(xiàn)dao層方法的接口
packagecom.hjf.service;importjava.util.List;importcom.hjf.dao.ClassDao;/*** CourseService
* 服務(wù)層
*@authorHDQ
**/
public classClassService {
ClassDao cDao= newClassDao();/*** 添加
*@paramcourse
*@return
*/
public booleanadd(String table,String strList[],String strList1[]) {boolean f =cDao.add(table,strList,strList1);returnf;
}/*** 刪除*/
public booleandel(String table,String qian,String hou) {returncDao.delete(table,qian,hou);
}/*** 修改
*@return
*/
public booleanupdate(String table,String []strlist,String []strlist1,String qian,String hou) {returncDao.update(table,strlist,strlist1,qian,hou);
}/*** 查找
*@return*@throwsIllegalAccessException
*@throwsInstantiationException*/
public List search(String table, String []strList, String []strList1,Class clazz) throwsInstantiationException, IllegalAccessException {returncDao.search(table,strList,strList1,clazz);
}/*** 由時(shí)間查找
*@return*@throwsIllegalAccessException
*@throwsInstantiationException*/
public List searchByTime(String table, String []strList, String []strList1,String biaoshi,String qian,String hou,Class clazz) throwsInstantiationException, IllegalAccessException {returncDao.searchByTime(table, strList, strList1, biaoshi, qian, hou, clazz);
}/*** 全部數(shù)據(jù)
*@return*@throwsIllegalAccessException
*@throwsInstantiationException
*@throwsClassNotFoundException*/
public List list(String table,String []strList,Class clazz) throwsClassNotFoundException, InstantiationException, IllegalAccessException {returncDao.list(table,strList,clazz);
}/*** 創(chuàng)建數(shù)據(jù)庫表單
*@return*@throwsIllegalAccessException
*@throwsInstantiationException*/
public boolean createTable(String table,String []info,String []type,int[]size)
{returncDao.createTable(table, info, type, size);
}
}
其3個(gè)類組成的工具類就如上面所示。
就以一個(gè)查找功能為例子,我現(xiàn)在Entity層中有3個(gè)類用到了這個(gè)通用類,假如現(xiàn)在想再定義一個(gè)新類調(diào)用這個(gè)通用數(shù)據(jù)庫的函數(shù),實(shí)現(xiàn)對(duì)數(shù)據(jù)庫對(duì)這個(gè)類的數(shù)據(jù)的增刪改查功能,以下就以一個(gè)具體的例子來展示如何調(diào)用這個(gè)通用類的函數(shù)
然后下面介紹這個(gè)通用類的用法:
首先假如現(xiàn)在有一個(gè)類,位于entity層,假如是一個(gè)老師類,Teacher
然后在entity層中定義一個(gè)Teacher類,其中含有int類型的編號(hào)id,String類型的名字name,還有Date類型的出生日期birth,(定義的類的多少不受限制),并定義getter和setter的方法
定義完這個(gè)類之后,數(shù)據(jù)庫里面對(duì)應(yīng)的項(xiàng)的名稱要和類的名稱一致,這樣才能被正確反射
所以在數(shù)據(jù)庫里面新建一個(gè)teacherlist的表,對(duì)應(yīng)的項(xiàng)的名稱設(shè)置為int類型的id,char或者text類型的name,Date類型的birth
名字分別都與Teacher類里面的名稱相對(duì)應(yīng)
雖然該工具類里面有提供表創(chuàng)建的函數(shù),但是為了方便讀者理解,這里用數(shù)據(jù)庫管理軟件的創(chuàng)建過程來展示
創(chuàng)建完成之后,要實(shí)現(xiàn)往這個(gè)數(shù)據(jù)庫的teacherlist里面添加數(shù)據(jù)的功能的話,我們查看一下service層提供的接口
這個(gè)是ClassServlet里面的前綴,ClassService就是數(shù)據(jù)庫通用工具的接口類,可以通過調(diào)用這個(gè)service里面的函數(shù)實(shí)現(xiàn)數(shù)據(jù)的操作
//--------------添加數(shù)據(jù)功能--------------
提供的方法是add(table,strList[],strList1[]),返回的類型是boolean類型,表示成功與否
第一個(gè)參數(shù)是table表名,第二個(gè)參數(shù)strList是需要添加的項(xiàng)的名稱字符串組,第三個(gè)參數(shù)strList1是對(duì)應(yīng)要需要添加項(xiàng)的內(nèi)容
例如執(zhí)行
String []strList=new String[] {"id","name","birth"};
String []strList1=new String[] {"11","王老師",“2001-09-22”};
service.add("teacherlist",strList,strList1);
就會(huì)將數(shù)據(jù)庫中teacherlist表里面對(duì)應(yīng)的id,name,birth項(xiàng)添加上11,王老師,2001-09-22的信息
值得注意的是,strLis[]里面的字符串要對(duì)應(yīng)和類中的變量名稱相等,而且數(shù)據(jù)庫中的名稱也是,這樣才能正確的反射,當(dāng)然,添加的過程并沒有用到反射,但是規(guī)范化而言,用到list等功能的時(shí)候就可以直接使用了。
當(dāng)出現(xiàn)數(shù)據(jù)添加失敗的時(shí)候,add函數(shù)會(huì)返回一個(gè)false,執(zhí)行成功時(shí)則是true
//--------------獲取列表信息功能--------------
首先上述是teacherlist數(shù)據(jù)庫表的信息,現(xiàn)在如果我們想把所有信息獲取到一個(gè)List里面,可以調(diào)用service提供的
獲取全部數(shù)據(jù)的方法
list(table,strlist[],Class);
其中參數(shù)table是要獲取數(shù)據(jù)的表格名稱,strList[]填寫的是要獲取數(shù)據(jù)庫中的哪個(gè)項(xiàng)的名稱所對(duì)應(yīng)的信息,Class是需要返回的List<>數(shù)組的類型,不過這個(gè)返回的類型一般還得強(qiáng)制轉(zhuǎn)換一下
以獲取上述的數(shù)據(jù)到一個(gè)List里面為例子,調(diào)用的函數(shù)如下所示:
String []strList=new String[]{"id","name","birth"};
@SuppressWarnings("unchecked")
List teachers= (List) service.list("teacherlist",strList,new Teacher().getClass());
此時(shí)teachers變量里面就儲(chǔ)存了你想要的數(shù)據(jù)了。然后,如果想要獲取的數(shù)據(jù)項(xiàng)沒有birth這個(gè)的話,在strList中填寫對(duì)應(yīng)想要獲取的數(shù)據(jù)項(xiàng)就可以了,String []strList=new String[]{"id","name"};再執(zhí)行獲取的函數(shù),這個(gè)時(shí)候獲取的teachers里面的birth就沒有儲(chǔ)存數(shù)據(jù)了
然后這里拓展一點(diǎn)小知識(shí),獲取的list可以存儲(chǔ)到attribute里面后直接在網(wǎng)頁上輸出,當(dāng)然要利用到j(luò)stl.jar和standard.jar這兩個(gè)包
這里調(diào)用tlist這個(gè)函數(shù)的時(shí)候,將會(huì)跳轉(zhuǎn)到teacherlist這個(gè)網(wǎng)頁
Insert title hereObjectmessage=request.getAttribute("message");if(message!=null &&!"".equals(message)){%>
alert("");
老師信息列表
返回主頁
編號(hào)id名字出生日期${item.id}${item.name}${item.birth}總結(jié)
以上是生活随笔為你收集整理的c mysql 工具类_Jave工具——servlet+jsp编程中mysql数据库连接及操作通用工具类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle性能优化求生指南_oracl
- 下一篇: golang mysql 自动建表_my