SQLHelper类(JAVA版)

  1. /**  
  2. *作者:devilishking  
  3. *email:devilishking@126.com  
  4. *  
  5. */  
  6.   
  7. package com.dal;   
  8.   
  9. import javax.sql.DataSource;   
  10. import javax.naming.*;   
  11. import java.sql.Connection;   
  12. import java.sql.PreparedStatement;   
  13. import java.sql.ResultSet;   
  14. import java.util.*;   
  15. import java.sql.*;   
  16.   
  17. public abstract class SQLHelper {   
  18.        
  19.     /**  
  20.      * 连接数据库  
  21.      *   
  22.      * @return  
  23.      */  
  24.     private static Connection getConnect() {   
  25.         try {   
  26.                
  27.             InitialContext context = new InitialContext();   
  28.             DataSource ds = (DataSource) context.lookup("java:/MSAccessDS");   
  29.                
  30.             return ds.getConnection();   
  31.         } catch (Exception e) {   
  32.             return null;   
  33.         }   
  34.     }   
  35.        
  36.     /**  
  37.      * 用于执行语句(eg:insert语句,update语句,delete语句)  
  38.      *   
  39.      * @param String  
  40.      *            cmdtext,SQL语句  
  41.      * @param OracleParameter[]  
  42.      *            parms,参数集合  
  43.      * @return int,SQL语句影响的行数  
  44.      */  
  45.     public static int ExecuteNonQuery(String cmdtext, String[] parms)   
  46.     throws Exception {   
  47.         PreparedStatement pstmt = null;   
  48.         Connection conn = null;   
  49.            
  50.         try {   
  51.             conn = getConnect();   
  52.             pstmt = conn.prepareStatement(cmdtext);   
  53.             prepareCommand(pstmt, parms);   
  54.                
  55.             return pstmt.executeUpdate();   
  56.                
  57.         } catch (Exception e) {   
  58.             throw new Exception("executeNonQuery方法出错:" + e.getMessage());   
  59.         } finally {   
  60.             try {   
  61.                 if (pstmt != null)   
  62.                     pstmt.close();   
  63.                 if (conn != null)   
  64.                     conn.close();   
  65.             } catch (Exception e) {   
  66.                 throw new Exception("执行executeNonQuery方法出错:" + e.getMessage());   
  67.             }   
  68.         }   
  69.     }   
  70.        
  71.     /**  
  72.      * 用于获取结果集语句(eg:selete * from table)  
  73.      *   
  74.      * @param cmdtext  
  75.      * @param parms  
  76.      * @return ResultSet  
  77.      * @throws Exception  
  78.      */  
  79.     public static ArrayList ExecuteReader(String cmdtext, String[] parms)   
  80.     throws Exception {   
  81.         PreparedStatement pstmt = null;   
  82.         Connection conn = null;   
  83.            
  84.         try {   
  85.             conn = getConnect();   
  86.                
  87.             pstmt = conn.prepareStatement(cmdtext);   
  88.                
  89.             prepareCommand(pstmt, parms);   
  90.             ResultSet rs = pstmt.executeQuery();   
  91.                
  92.             ArrayList al = new ArrayList();   
  93.             ResultSetMetaData rsmd = rs.getMetaData();   
  94.             int column = rsmd.getColumnCount();   
  95.                
  96.             while (rs.next()) {   
  97.                 Object[] ob = new Object[column];   
  98.                 for (int i = 1; i <= column; i++) {   
  99.                     ob[i - 1] = rs.getObject(i);   
  100.                 }   
  101.                 al.add(ob);   
  102.             }   
  103.                
  104.             rs.close();   
  105.             return al;   
  106.                
  107.         } catch (Exception e) {   
  108.             throw new Exception("executeSqlResultSet方法出错:" + e.getMessage());   
  109.         } finally {   
  110.             try {   
  111.                 if (pstmt != null)   
  112.                     pstmt.close();   
  113.                 if (conn != null)   
  114.                     conn.close();   
  115.             } catch (Exception e) {   
  116.                 throw new Exception("executeSqlResultSet方法出错:" + e.getMessage());   
  117.             }   
  118.         }   
  119.     }   
  120.        
  121.     /**  
  122.      * 用于获取单字段值语句(用名字指定字段)  
  123.      *   
  124.      * @param cmdtext  
  125.      *            SQL语句  
  126.      * @param name  
  127.      *            列名  
  128.      * @param parms  
  129.      *            OracleParameter[]  
  130.      * @return Object  
  131.      * @throws Exception  
  132.      */  
  133.     public static Object ExecuteScalar(String cmdtext, String name,   
  134.             String[] parms) throws Exception {   
  135.         PreparedStatement pstmt = null;   
  136.         Connection conn = null;   
  137.         ResultSet rs = null;   
  138.            
  139.         try {   
  140.             conn = getConnect();   
  141.                
  142.             pstmt = conn.prepareStatement(cmdtext);   
  143.             prepareCommand(pstmt, parms);   
  144.                
  145.             rs = pstmt.executeQuery();   
  146.             if (rs.next()) {   
  147.                 return rs.getObject(name);   
  148.             } else {   
  149.                 return null;   
  150.             }   
  151.         } catch (Exception e) {   
  152.             throw new Exception("executeSqlObject方法出错:" + e.getMessage());   
  153.         } finally {   
  154.             try {   
  155.                 if (rs != null)   
  156.                     rs.close();   
  157.                 if (pstmt != null)   
  158.                     pstmt.close();   
  159.                 if (conn != null)   
  160.                     conn.close();   
  161.             } catch (Exception e) {   
  162.                 throw new Exception("executeSqlObject方法出错:" + e.getMessage());   
  163.             }   
  164.         }   
  165.     }   
  166.        
  167.     /**  
  168.      * 用于获取单字段值语句(用序号指定字段)  
  169.      *   
  170.      * @param cmdtext  
  171.      *            SQL语句  
  172.      * @param index  
  173.      *            列名索引  
  174.      * @param parms  
  175.      *            OracleParameter[]  
  176.      * @return Object  
  177.      * @throws Exception  
  178.      */  
  179.     public static Object ExecuteScalar(String cmdtext, int index, String[] parms)   
  180.     throws Exception {   
  181.         PreparedStatement pstmt = null;   
  182.         Connection conn = null;   
  183.         ResultSet rs = null;   
  184.            
  185.         try {   
  186.             conn = getConnect();   
  187.                
  188.             pstmt = conn.prepareStatement(cmdtext);   
  189.             prepareCommand(pstmt, parms);   
  190.                
  191.             rs = pstmt.executeQuery();   
  192.             if (rs.next()) {   
  193.                 return rs.getObject(index);   
  194.             } else {   
  195.                 return null;   
  196.             }   
  197.         } catch (Exception e) {   
  198.             throw new Exception("executeSqlObject方法出错:" + e.getMessage());   
  199.         } finally {   
  200.             try {   
  201.                 if (rs != null)   
  202.                     rs.close();   
  203.                 if (pstmt != null)   
  204.                     pstmt.close();   
  205.                 if (conn != null)   
  206.                     conn.close();   
  207.             } catch (Exception e) {   
  208.                 throw new Exception("executeSqlObject方法出错:" + e.getMessage());   
  209.             }   
  210.         }   
  211.     }   
  212.        
  213.     /**  
  214.      * @param pstmt  
  215.      * @param cmdtext  
  216.      * @param parms  
  217.      *            Object[]  
  218.      * @throws Exception  
  219.      */  
  220.     private static void prepareCommand(PreparedStatement pstmt, String[] parms)   
  221.     throws Exception {   
  222.         try {   
  223.             if (parms != null) {   
  224.                 for (int i = 0; i < parms.length; i++) {   
  225.                     try {   
  226.                         pstmt.setDate(i + 1, java.sql.Date.valueOf(parms[i]));   
  227.                     } catch (Exception e) {   
  228.                         try {   
  229.                             pstmt   
  230.                             .setDouble(i + 1, Double   
  231.                                     .parseDouble(parms[i]));   
  232.                         } catch (Exception e1) {   
  233.                             try {   
  234.                                 pstmt.setInt(i + 1, Integer.parseInt(parms[i]));   
  235.                             } catch (Exception e2) {   
  236.                                 try {   
  237.                                     pstmt.setString(i + 1, parms[i]);   
  238.                                 } catch (Exception e3) {   
  239.                                     System.out   
  240.                                     .print("SQLHelper-PrepareCommand Err1:"  
  241.                                             + e3);   
  242.                                 }   
  243.                             }   
  244.                         }   
  245.                     }   
  246.                 }   
  247.             }   
  248.         } catch (Exception e1) {   
  249.             System.out.print("SQLHelper-PrepareCommand Err2:" + e1);   
  250.         }   
  251.     }   
  252. }  
/**
*作者:devilishking
*email:devilishking@126.com
*
*/

package com.dal;

import javax.sql.DataSource;
import javax.naming.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.sql.*;

public abstract class SQLHelper {
	
	/**
	 * 连接数据库
	 * 
	 * @return
	 */
	private static Connection getConnect() {
		try {
			
			InitialContext context = new InitialContext();
			DataSource ds = (DataSource) context.lookup("java:/MSAccessDS");
			
			return ds.getConnection();
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 用于执行语句(eg:insert语句,update语句,delete语句)
	 * 
	 * @param String
	 *            cmdtext,SQL语句
	 * @param OracleParameter[]
	 *            parms,参数集合
	 * @return int,SQL语句影响的行数
	 */
	public static int ExecuteNonQuery(String cmdtext, String[] parms)
	throws Exception {
		PreparedStatement pstmt = null;
		Connection conn = null;
		
		try {
			conn = getConnect();
			pstmt = conn.prepareStatement(cmdtext);
			prepareCommand(pstmt, parms);
			
			return pstmt.executeUpdate();
			
		} catch (Exception e) {
			throw new Exception("executeNonQuery方法出错:" + e.getMessage());
		} finally {
			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e) {
				throw new Exception("执行executeNonQuery方法出错:" + e.getMessage());
			}
		}
	}
	
	/**
	 * 用于获取结果集语句(eg:selete * from table)
	 * 
	 * @param cmdtext
	 * @param parms
	 * @return ResultSet
	 * @throws Exception
	 */
	public static ArrayList ExecuteReader(String cmdtext, String[] parms)
	throws Exception {
		PreparedStatement pstmt = null;
		Connection conn = null;
		
		try {
			conn = getConnect();
			
			pstmt = conn.prepareStatement(cmdtext);
			
			prepareCommand(pstmt, parms);
			ResultSet rs = pstmt.executeQuery();
			
			ArrayList al = new ArrayList();
			ResultSetMetaData rsmd = rs.getMetaData();
			int column = rsmd.getColumnCount();
			
			while (rs.next()) {
				Object[] ob = new Object[column];
				for (int i = 1; i <= column; i++) {
					ob[i - 1] = rs.getObject(i);
				}
				al.add(ob);
			}
			
			rs.close();
			return al;
			
		} catch (Exception e) {
			throw new Exception("executeSqlResultSet方法出错:" + e.getMessage());
		} finally {
			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e) {
				throw new Exception("executeSqlResultSet方法出错:" + e.getMessage());
			}
		}
	}
	
	/**
	 * 用于获取单字段值语句(用名字指定字段)
	 * 
	 * @param cmdtext
	 *            SQL语句
	 * @param name
	 *            列名
	 * @param parms
	 *            OracleParameter[]
	 * @return Object
	 * @throws Exception
	 */
	public static Object ExecuteScalar(String cmdtext, String name,
			String[] parms) throws Exception {
		PreparedStatement pstmt = null;
		Connection conn = null;
		ResultSet rs = null;
		
		try {
			conn = getConnect();
			
			pstmt = conn.prepareStatement(cmdtext);
			prepareCommand(pstmt, parms);
			
			rs = pstmt.executeQuery();
			if (rs.next()) {
				return rs.getObject(name);
			} else {
				return null;
			}
		} catch (Exception e) {
			throw new Exception("executeSqlObject方法出错:" + e.getMessage());
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e) {
				throw new Exception("executeSqlObject方法出错:" + e.getMessage());
			}
		}
	}
	
	/**
	 * 用于获取单字段值语句(用序号指定字段)
	 * 
	 * @param cmdtext
	 *            SQL语句
	 * @param index
	 *            列名索引
	 * @param parms
	 *            OracleParameter[]
	 * @return Object
	 * @throws Exception
	 */
	public static Object ExecuteScalar(String cmdtext, int index, String[] parms)
	throws Exception {
		PreparedStatement pstmt = null;
		Connection conn = null;
		ResultSet rs = null;
		
		try {
			conn = getConnect();
			
			pstmt = conn.prepareStatement(cmdtext);
			prepareCommand(pstmt, parms);
			
			rs = pstmt.executeQuery();
			if (rs.next()) {
				return rs.getObject(index);
			} else {
				return null;
			}
		} catch (Exception e) {
			throw new Exception("executeSqlObject方法出错:" + e.getMessage());
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e) {
				throw new Exception("executeSqlObject方法出错:" + e.getMessage());
			}
		}
	}
	
	/**
	 * @param pstmt
	 * @param cmdtext
	 * @param parms
	 *            Object[]
	 * @throws Exception
	 */
	private static void prepareCommand(PreparedStatement pstmt, String[] parms)
	throws Exception {
		try {
			if (parms != null) {
				for (int i = 0; i < parms.length; i++) {
					try {
						pstmt.setDate(i + 1, java.sql.Date.valueOf(parms[i]));
					} catch (Exception e) {
						try {
							pstmt
							.setDouble(i + 1, Double
									.parseDouble(parms[i]));
						} catch (Exception e1) {
							try {
								pstmt.setInt(i + 1, Integer.parseInt(parms[i]));
							} catch (Exception e2) {
								try {
									pstmt.setString(i + 1, parms[i]);
								} catch (Exception e3) {
									System.out
									.print("SQLHelper-PrepareCommand Err1:"
											+ e3);
								}
							}
						}
					}
				}
			}
		} catch (Exception e1) {
			System.out.print("SQLHelper-PrepareCommand Err2:" + e1);
		}
	}
}



Ⅰ.引言
使用该类目的就是让使用者更方便、更安全的对数据库的操作,既是除了在SQLHelper类以外的所有类将不用引用对数据库操作的任何类与语句,无须担心数据库的连接与关闭的问题。但是,该类仍然需要大量的调试与修改。故此,请使用者不断完善该类,以至于能与SQLHelper(.NET版)的功能并驾齐驱。

Ⅱ.注意事项
1. 使用前设置
手动修改以下代码段为当前连接数据库的代码段
private static Connection getConnect() {
try {
//修改代码段
} catch (Exception e) {
return null;
}
}
2. SQLHelper类支持数据库字段类型
1) 文本类型
2) 带符号整数类型
3) 双精度浮点数类型
4) 日期类型

注意:如果没有想要的类时,请手动添加到以下方法内
private static void prepareCommand(PreparedStatement pstmt, String[] parms)
throws Exception {
//代码段
}
另外,添加时请注意“从特殊到常用”原则,即将最特殊的类型放到try/catch语句的最高级的代码段区,将最常用的类型放到try/catch语句的最低级的代码段区。

Ⅲ.类方法说明
注意:正文内出现“【】”的区域在使用的时候必须进行相应替换,而“『』”的区域为替换的可选项。
1. SQLHelper.ExecuteNonQuery
作用:用于执行语句
返回类型:int
格式:
boolean state = false;
try {
String[] parms = {【参数区(如果类型为非String型,则"" + 变量)】};
int i = SQLHelper.ExecuteNonQuery(【SQL语句】, parms『可为null』);
if (i == 1) {
state = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return state;
2. SQLHelper.ExecuteScalar
作用:用于获取单字段值语句
返回类型:Object
格式:
【变量类型】 【变量】 = 【初始化变量】
try {
String[] parms = { 【参数区(如果类型为非String型,则"" + 变量)】};
【变量】 = 『强制转换为变量的类型』SQLHelper.ExecuteScalar(【SQL语句】, 【列名或列名索引】, parms『可为null』)
.toString();
} catch (Exception e) {
e.printStackTrace();
}
return 【变量】;

3. SQLHelper.ExecuteReader
作用:用于获取结果集语句
返回类型:java.util.ArrayList
格式:
ArrayList al = new ArrayList();
try {
String[] parms = { 【参数区(如果类型为非String型,则"" + 变量)】};
al = SQLHelper.ExecuteReader(【SQL语句】, parms『可为null』);
al = getArrayListValues(al);
} catch (Exception e) {
errMessage = e.toString();
}
return al;

另外,添加以下两个函数:

//根据结果集获取其全部信息
private ArrayList getArrayListValues(ArrayList arrayList) throws Exception {
ArrayList al2 = new ArrayList();
for (int i = 0; i < arrayList.size(); i++) {
al2.add(getOneRowValues(i, new 【最终存放数据的变量类型】, arrayList));
}
return al2;
}

//根据行索引,获取其一行的所有信息
private TbUserBLL getOneRowValues(int i, 【最终存放数据的变量类型】【最终存放数据的变量】, ArrayList arrayList) throws Exception {
Object[] ob = (Object[]) arrayList.get(i);
【最终存放数据的变量】.setXX=『强制转换为其属性类型』ob[0].toString();

【最终存放数据的变量】.setXX=『强制转换为其属性类型』ob[X].toString();
return【最终存放数据的变量】;
}

Ⅳ.测试列表
注意:如果再对该类进行测试时,请按以下格式添加说明。
1.测试一
连接数据库方式:jdbc-odbc桥
使用数据库:Access
测试内容:对SQLHelper各方法的使用情况测试
测试人员:刘冀超
测试结果:成功。

Ⅴ.测试工具说明
1.数据库表
TbUser【用户表】

字段名 数据结构 允许空值 说  明
tbUserID int 否 用户编号
tbUserName varchar(20) 否 用户姓名
tbUserPwd varchar(20) 否 用户密码
tbUserRole int 否 用户角色

2.测试页面(Index.jsp)
说明:该页面包含了所有间接调用SQLHelper所提供的方法(即ExecuteNonQuery,ExecuteScalar,ExecuteReader)。如有需要请再以下标签前添加功能,
<tr>
    <td align="center" class="STYLE3">测试结果</td>
</tr>
并按照内部格式将错误信息放入errMessage的变量内。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 SQLHelper ,使用 JavaJDBC 进行数据库操作: ```java import java.sql.*; public class SQLHelper { private Connection conn = null; private Statement stmt = null; private ResultSet rs = null; public SQLHelper(String url, String user, String password) throws SQLException { conn = DriverManager.getConnection(url, user, password); stmt = conn.createStatement(); } public ResultSet executeQuery(String sql) throws SQLException { rs = stmt.executeQuery(sql); return rs; } public int executeUpdate(String sql) throws SQLException { return stmt.executeUpdate(sql); } public void close() throws SQLException { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } ``` 使用该可以执行 SQL 查询和更新操作。例如,查询语句可以这样执行: ```java String url = "jdbc:mysql://localhost:3306/mydb"; String user = "root"; String password = "root"; SQLHelper sqlHelper = new SQLHelper(url, user, password); String sql = "SELECT * FROM mytable"; ResultSet rs = sqlHelper.executeQuery(sql); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); System.out.println("id=" + id + ", name=" + name + ", age=" + age); } sqlHelper.close(); ``` 更新语句可以这样执行: ```java String url = "jdbc:mysql://localhost:3306/mydb"; String user = "root"; String password = "root"; SQLHelper sqlHelper = new SQLHelper(url, user, password); String sql = "UPDATE mytable SET name='Alice' WHERE id=1"; int rowsAffected = sqlHelper.executeUpdate(sql); System.out.println(rowsAffected + " rows affected"); sqlHelper.close(); ``` 注意,这只是一个简单的 SQLHelper ,实际应用中需要考虑更多的异常处理、连接池等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值