java的mysql api封裝
阿新 • • 發佈:2019-02-20
Mysql api函式:具體的api操作
package com.fasterry.dao;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.hql.internal.ast.tree.IsNotNullLogicOperatorNode;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class Mysql {
private static volatile Mysql instance = null;
public static final String url = "jdbc:mysql://localhost:3306/Evaluation";
public String db = "company?autoReconnect=true";
public static final String driver = "com.mysql.jdbc.Driver";
public static final String user = "zhouchenglin";
public static final String password = "zhouchenglin";
public Connection connection = null;
public PreparedStatement pstmt = null;
public ResultSet resultSet = null;
public static Mysql getInstance() {
if (instance == null) {
synchronized (Mysql.class) {
if (instance == null) {
instance = new Mysql();
}
}
}
return instance;
}
public Mysql() {
try {
// 指定連線型別
Class.forName(driver);
// 獲取連線
connection = (Connection) DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
}
public int queryCount(String sql,List<Object> params) throws SQLException{
int count = 0;
int index = 1;
pstmt = (PreparedStatement) 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();
count = resultSet.getFetchSize();
return count;
}
public Map<String, Object> queryOne(String sql, List<Object> params) throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
int index = 1;
pstmt = (PreparedStatement) 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);
}
}
return map;
}
public void insertData(String sql, List<Object> params) throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
int index = 1;
pstmt = (PreparedStatement) connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
pstmt.executeUpdate();
}
public List<Map<String, Object>> queryMore(String sql, List<Object> params) throws SQLException {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
int index = 1;
pstmt = (PreparedStatement) 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<String, Object> map = new HashMap<String, Object>();
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);
}
return list;
}
protected void finalize() throws Throwable {
super.finalize();
connection.close();
}
}
mysqlAPi封裝:通過將sql語句放在sql.properties檔案裡面,來將所有的sql語句放在同一個檔案裡面,來操作。
package com.fasterry.dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.taglibs.standard.lang.jstl.test.beans.PublicInterface2;
import com.fasterry.dao.*;
import com.fasterry.test.test;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class MysqlAPI {
private Mysql mysql;
private Properties prs;
/**
* 建構函式,初始化sql.properties
*
* @throws IOException
*/
public MysqlAPI() throws IOException {
prs = new Properties();
InputStream inputStream = test.class.getResourceAsStream("../properties/sql.properties");
mysql = Mysql.getInstance();
prs.load(inputStream);
inputStream.close();
}
/**
* 向資料庫插入一條資料
*
* @param sqlKey
* key的值,通過尋找sql.propertie檔案來獲得對應的sql
* @param params
* 插入的資料
* @return 插入失敗的返回值
*/
public String InsertData(String sqlKey, List<Object> params) {
String sql = prs.getProperty(sqlKey);
String error = null;
try {
mysql.insertData(sql, params);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
error = "插入失敗";
}
return error;
}
public int queryCount(String sqlKey, List<Object> params) {
String sql = prs.getProperty(sqlKey);
int count = 0;
try {
count = mysql.queryCount(sql, params);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
/**
* 查詢一條資料,並返回json物件
*
* @param sqlKey
* sql.properties檔案裡面的key
* @param params
* 要查詢的引數
* @return json物件
*/
public JSONObject queryOne(String sqlKey, List<Object> params) {
JSONObject json = null;
String sql = prs.getProperty(sqlKey);
Map<String, Object> map = new HashMap<String, Object>();
try {
map = mysql.queryOne(sql, params);
json = JSONObject.fromObject(map);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
/**
* 查詢多條資料,並返回json物件
*
* @param sqlKey
* sql.properties檔案裡面的key
* @param params
* 要查詢的引數
* @return json物件
*/
public JSONArray queryMore(String sqlKey, List<Object> params) {
JSONArray json = null;
String sql = prs.getProperty(sqlKey);
try {
List<Map<String, Object>> list = mysql.queryMore(sql, params);
json = JSONArray.fromObject(list);
} catch (SQLException e) {
e.printStackTrace();
}
return json;
}
/**
* 尋找指定字串的個數
*
* @param str
* 指定字串
* @param key
* 要查詢的字元
* @return key的個數
*/
public int findKeyString(String str, String key) {
int num = 0;
while (str.indexOf(key) != -1) {
num++;
str = str.substring(str.indexOf(key) + key.length());
}
return num;
}
}
sql.properties
#/*********************user表*****************
insertUser=insert into user(name,password) values(?,?)
queryUserInfo=select name,password,age from user
queryUserPassword=select password from user where name=?
queryUserName=select count(*) from user where name=?
我個人覺得將sql語句放在同一個檔案裡面來操作比較好,這樣更加方便的管理sql語句。