本次使用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 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> commonQuery(String sql_string) throws SQLException {
Connection connection = getConnection();
Statement statement = (Statement) connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql_string);
ArrayList> arraylist = new ArrayList>();
int column_count =resultSet.getMetaData().getColumnCount();
while(resultSet.next()) {
ArrayList
简单使用实例如下
比如操作表:
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 customer = new HashMap();
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 wheres = new HashMap();
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 wheres = new HashMap();
wheres.put("id", new Object[] {new Integer(37),"=","and"});
try {
MaprowResult = 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 values = new HashMap();
Map wheres = new HashMap();
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();
}
以上内容仅做个人备忘用
转载于:https://blog.51cto.com/quietnight/2300328