jdbc中對mysql數據庫操作的簡單封裝--(僅做備忘記錄)
阿新 • • 發佈:2018-10-16
nihao lse bin javaee sub getc eva 目的 web-inf 本次使用jdbc中的mysql-connector-java-5.1.47-bin.jar的連接包,下載這個jar包放在javaee項目的WEB-INF/lib目錄下,再把它作為外包jar包進入到libraries中,這樣就可以使用mysql的jdbc接口了。
自己封裝的代碼中引入了兩個自己字義的Exception:
SqlSecureException.java
package com.myproweb.exception; public class SqlSecureException extends Exception { /** * */ private static final long serialVersionUID = -185202535331616389L; }
SqlErrorException.java
package com.myproweb.exception;
public class SqlSecureException extends Exception {
/**
*
*/
private static final long serialVersionUID = -185202535331616389L;
}
最後封裝代碼如下:
package com.myproweb.utils; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.myproweb.exception.SqlErrorException; import com.myproweb.exception.SqlSecureException; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; public class MysqlDatabaseConnection { private static String mysql_username = "root"; private static String mysql_password = ""; private static String mysql_connection_url = "jdbc:mysql://localhost:3306/javadb"; private static Connection mysql_connection; private static Boolean check_fileds_safety = true; static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private static Boolean validateValueString(String value_string) { value_string = value_string.toLowerCase(); String validateString="‘|or|and|;|-|--|+|,|like|//|/|*|%|#"; String[] validateStrings = validateString.split("\\|"); for (int i = 0; i < validateStrings.length; i++) { if (value_string.indexOf(validateStrings[i]) >= 0) { return false; } } return true; } private static String getSqlValue(Object obj) throws SqlSecureException { String sql_value_string = null; if (obj instanceof String) { if(check_fileds_safety){ if(validateValueString(obj.toString().trim())) { sql_value_string = "‘" + obj.toString().trim() + "‘"; }else { throw new SqlSecureException(); } }else { sql_value_string = "‘" + obj.toString().trim() + "‘"; } } if (obj instanceof Integer) { sql_value_string = ((Integer) obj).toString(); } if (obj instanceof Long) { sql_value_string = ((Long) obj).toString(); } if (obj instanceof Float) { sql_value_string = ((Float) obj).toString(); } if (obj instanceof Double) { sql_value_string = ((Double) obj).toString(); } return sql_value_string; } private static String getWheresSqlString(Map<String, Object[]> wheres) throws SqlErrorException, SqlSecureException { String where_string = ""; for (String key : wheres.keySet()) { Object[] condition = wheres.get(key); String value_string = getSqlValue(condition[0]); if (condition.length == 1) { if (null != value_string) { if ("".equals(where_string)) { where_string += " " + key.trim() + "=" + value_string + " "; } else { where_string += "and " + key.trim() + "=" + value_string + " "; } } } if (condition.length == 2) { if (!(condition[1] instanceof String)) { throw new SqlErrorException("key words error[0001]!"); } String judgement_condition = condition[1].toString().trim(); if ("=".equals(judgement_condition) || "<=".equals(judgement_condition) || ">=".equals(judgement_condition) || "!=".equals(judgement_condition) || "<>".equals(judgement_condition)) { if (null != value_string) { if ("".equals(where_string)) { where_string += " " + key.trim() + judgement_condition + value_string + " "; } else { where_string += "and " + key.trim() + judgement_condition + value_string + " "; } } } else { throw new SqlErrorException("key words error[0002]!"); } } if (condition.length == 3) { if (!(condition[2] instanceof String) || !(condition[1] instanceof String)) { throw new SqlErrorException("key words error[0001]!"); } String and_or_string = condition[2].toString().toUpperCase(); String judgement_condition = condition[1].toString().trim(); if (("AND".equals(and_or_string) || "OR".equals(and_or_string)) && ("=".equals(judgement_condition) || "<=".equals(judgement_condition) || ">=".equals(judgement_condition) || "!=".equals(judgement_condition) || "<>".equals(judgement_condition))) { if (!"".equals(where_string)) { where_string += and_or_string + ‘ ‘; } if (null != value_string) { where_string += key.trim() + judgement_condition + value_string + ‘ ‘; } } else { throw new SqlErrorException("key words error[0002]!"); } } } if ("".equals(where_string)) { throw new SqlErrorException("key words error[0003]!"); } return where_string; } /** * 是否設置對字符值進行安全檢查 * @param is_fields_safety true:進行安全檢查 false:不進行安全檢查 */ public static void setFieldsSecure(Boolean is_fields_safety) { check_fileds_safety=is_fields_safety; } // 連接數據庫邊接 public static Connection getConnection() throws SQLException { if (null != mysql_connection) { close(mysql_connection); } mysql_connection = (Connection) DriverManager.getConnection(mysql_connection_url, mysql_username, mysql_password); return mysql_connection; } /** * 通用的刪除、更新、刪除函數 * @param sql_string delete or update or insert sql語句 * @return sql操作影響的行數 * @throws SQLException */ public static int commonDeleteOrUpdateOrInsert(String sql_string) throws SQLException { Connection connection = getConnection(); Statement statement = (Statement) connection.createStatement(); int result = statement.executeUpdate(sql_string); close(connection); close(statement); return result; } /** * 通用的查詢函數 * @param sql_string select sql語句 * @return 把查詢的結果集放到一個二唯數組中 * @throws SQLException */ public static ArrayList<ArrayList<Object>> commonQuery(String sql_string) throws SQLException { Connection connection = getConnection(); Statement statement = (Statement) connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql_string); ArrayList<ArrayList<Object>> arraylist = new ArrayList<ArrayList<Object>>(); int column_count =resultSet.getMetaData().getColumnCount(); while(resultSet.next()) { ArrayList<Object> tmp_arraylist = new ArrayList<Object>(); for(int i=1 ;i<=column_count ; i++) { tmp_arraylist.add(resultSet.getObject(i)); } arraylist.add(tmp_arraylist); } close(resultSet); close(statement); close(connection); return arraylist; } /** * 實現一個簡單sql插入的封裝 * * @param table_name 表名 * @param values 要插入的值 * @return 返回Statement執行的結果 * @throws SQLException * @throws SqlSecureException */ public static int simplyInsert(String table_name, Map<String, Object> values) throws SQLException, SqlSecureException { String sql_string = "insert into " + table_name; String fields_string = ""; String values_string = ""; for (String key : values.keySet()) { fields_string += key.trim() + ‘,‘; Object obj = values.get(key); String t_value_string = getSqlValue(obj); if (null != t_value_string) { values_string += t_value_string + ","; } } fields_string = fields_string.substring(0, fields_string.length() - 1); values_string = values_string.substring(0, values_string.length() - 1); sql_string = sql_string + "(" + fields_string + ") value(" + values_string + ")"; return commonDeleteOrUpdateOrInsert(sql_string); } /** * 實現一個簡單sql更新封裝 * @param table_name 表名 * @param values 更新的值 * @param wheres 更新的條件 * @return 返回受影響的行數 * @throws SqlErrorException * @throws SQLException * @throws SqlSecureException */ public static int simplyUpdate(String table_name, Map<String, Object> values, Map<String, Object[]> wheres) throws SqlErrorException, SQLException, SqlSecureException { String sql_string="update "+table_name+" set "; String update_string =""; for(String key:values.keySet()) { update_string+=key+"="+getSqlValue(values.get(key))+","; } if("".equals(update_string)) { throw new SqlErrorException("update string is error!"); } update_string = update_string.substring(0, update_string.length() - 1); String where_string = getWheresSqlString(wheres); sql_string+=update_string+" where "+where_string; return commonDeleteOrUpdateOrInsert(sql_string); } /** * 實現一個簡單sql查詢一條結果封裝 * @param table_name 表名 * @param fields 字符集 * @param wheres 條件 * @return 返回一行結果 * @throws SqlErrorException * @throws SQLException * @throws SqlSecureException */ public static Map<String,Object> simplyQueryRow(String table_name, String[] fields, Map<String, Object[]> wheres) throws SqlErrorException, SQLException, SqlSecureException { String sql_string = "select "; String fields_string = ""; if (fields.length == 0) { throw new SqlErrorException("fileds do not allowed empty!"); } for (String field : fields) { fields_string += field + ","; } fields_string = fields_string.substring(0, fields_string.length() - 1); sql_string += fields_string + " from " + table_name + " where "; String where_string = getWheresSqlString(wheres); sql_string += where_string+" limit 1"; ArrayList<ArrayList<Object>> resultSet = commonQuery(sql_string); Map<String,Object> result = new HashMap<String,Object>(); ArrayList<Object> filst_row = resultSet.get(0); if(null != filst_row) { int column_size =filst_row.size(); if(column_size==fields.length) { for(int i=0;i < fields.length ; i++) { result.put(fields[i], filst_row.get(i)); } }else { throw new SqlErrorException("fileds and result is error!"); } } return result; } /*** * 一個簡單的刪除封裝 * @param table_name 表名 * @param wheres 條件集 * @return 返回受影響的行 * @throws SqlErrorException * @throws SQLException * @throws SqlSecureException */ public static int simplyDelete(String table_name, Map<String, Object[]> wheres) throws SqlErrorException, SQLException, SqlSecureException { String sql_string = "delete from " + table_name + " where "; String where_string = getWheresSqlString(wheres); sql_string += where_string; return commonDeleteOrUpdateOrInsert(sql_string); } // 關閉 結果集 sql預聲明 連接 public static void close(Object obj) throws SQLException { if (null == obj) { return; } if (obj instanceof ResultSet) { ((ResultSet) obj).close(); } if (obj instanceof Statement) { ((Statement) obj).close(); } if (obj instanceof Connection) { ((Connection) obj).close(); } obj = null; } }
簡單使用實例如下
比如操作表:
CREATE TABLE `customer` ( `id` int(8) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(20) NOT NULL COMMENT ‘用戶名‘, `password` varchar(20) NOT NULL COMMENT ‘密碼‘, `gender` int(1) NOT NULL DEFAULT ‘0‘ COMMENT ‘性別‘, PRIMARY KEY (`id`), UNIQUE KEY `customer_id` (`id`) USING BTREE, KEY `customer_username` (`username`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=utf8 COMMENT=‘用戶表‘;
MysqlDatabaseConnection.simplyInsert 方法示例:
HashMap<String,Object> customer = new HashMap<String,Object>();
customer.put("username", "admin");
customer.put("password", "123123123");
customer.put("gender", new Integer(1));
try {
int result = MysqlDatabaseConnection.simplyInsert("customer",customer );
System.out.println(result);
} catch (SQLException e) {
e.printStackTrace();
} catch (SqlSecureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MysqlDatabaseConnection.simplyDelete 方法示例:
Map<String,Object []> wheres = new HashMap<String,Object []>();
wheres.put("id", new Object[] {new Integer(6),"<=","and"});
wheres.put("username", new Object[] {"jack","=","or"});
try {
int result = MysqlDatabaseConnection.simplyDelete("customer", wheres);
System.out.println(result);
} catch (SqlErrorException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (SqlSecureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MysqlDatabaseConnection.simplyQueryRow 方法示例:
Map<String,Object []> wheres = new HashMap<String,Object []>();
wheres.put("id", new Object[] {new Integer(37),"=","and"});
try {
Map<String,Object>rowResult = MysqlDatabaseConnection.simplyQueryRow("customer", new String[] {"id","username","password","gender"}, wheres);
for(String key:rowResult.keySet()) {
System.out.println(key+":"+rowResult.get(key));
}
} catch (SqlErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SqlSecureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MysqlDatabaseConnection.simplyUpdate 方法示例:
Map<String,Object> values = new HashMap<String,Object>();
Map<String,Object[]> wheres = new HashMap<String,Object[]>();
values.put("username", "admin1");
values.put("password", "nihao");
wheres.put("id", new Object[] {new Integer(31)});
try {
int result = MysqlDatabaseConnection.simplyUpdate("customer", values, wheres);
System.out.println(result);
} catch (SqlErrorException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (SqlSecureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
以上內容僅做個人備忘用
jdbc中對mysql數據庫操作的簡單封裝--(僅做備忘記錄)