安卓直連SQLSEVER數據庫


1、導入連接SQLSEVER的jar包:可以支持android的SQL驅動(如:jtds-1.2.7.jar

2、編寫連接數據庫的工具類

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Connection;
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 static android.text.TextUtils.split;

//數據庫得開啟TCP/IP功能 的1433端口
public class DBUtil {

//數據庫
private static String IP = "192.168.1.666"; //類似的IP地址IP地址
private static String DBName = "XXX"; //數據庫名
private static String USER = "XX";
private static String PWD = "XXX";


/**
* 創建數據庫對象
*/
public static Connection getSQLConnection() {
Connection con = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
//加上 useunicode=true;characterEncoding=UTF-8 防止中文亂碼
con = DriverManager.getConnection("jdbc:jtds:sqlserver://" + IP + ":1433/" + DBName + ";useunicode=true;characterEncoding=UTF-8", USER, PWD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}


/**
* 返回的List的[1]數據時List<Map>
* @param sql
* @return
* @throws
*/
//region 傳入sql,返回轉換成List(查詢)
public static List Query(String sql) {
List result = new ArrayList();
ResultSet rs = null;
try {
Connection conn = getSQLConnection();

Statement stmt = conn.createStatement();//
rs = stmt.executeQuery(sql);
result = convertList(rs);
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
String res = "查詢數據異常" + e.getMessage();
e.printStackTrace();
result.add(res);
return result;
} catch (Exception e) {
String res = "無網絡";
result.add(res);
return result;
}

return result;
}

//返回list,ResultSet轉List<map>
public static List convertList(ResultSet rs) throws SQLException {
List all = new ArrayList();
List list = new ArrayList();
ResultSetMetaData md = rs.getMetaData();//獲取鍵名
int columnCount = md.getColumnCount();//獲取行的數量
String res = "ok";


all.add(res);
int coun = 0;
while (rs.next()) {
Map rowData = new HashMap();//聲明Map
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));//獲取鍵名及值
}
list.add(rowData);
coun++;
}
if (coun < 1) {
all.set(0, "nodate");
}
all.add(list);

return all;
}
//endregion


/**
* 更新數據,新增,修改,刪除
*/
//region 更新數據,新增,修改,刪除 返回int
public static int exesqlint(String sql){
int rs = 0;
try {

Connection conn = getSQLConnection();
Statement stmt = conn.createStatement();//
rs = stmt.executeUpdate(sql);
stmt.close();
conn.close();
} catch (SQLException e) {
String res = "查詢數據異常" + e.getMessage();
e.printStackTrace();
return 0;
} catch (Exception e) {
return 0;
}

return rs;
}
//endregion

//region 更新數據,新增,修改,刪除 返回LIST數據
public static List exesql(String sql) {
List result = new ArrayList();
int rs = 0;
try {
String ress = "";
Connection conn = getSQLConnection();

Statement stmt = conn.createStatement();//
rs = stmt.executeUpdate(sql);
if (rs > 0) {
ress = "ok";
} else {
ress = "nodate";
}
result.add(ress);
stmt.close();
conn.close();
} catch (SQLException e) {
String res = "查詢數據異常" + e.getMessage();
e.printStackTrace();
result.add(res);
return result;
} catch (Exception e) {
String res = "無網絡";
result.add(res);
return result;
}
return result;
}



//endregion

/**
* 查詢,有無該條數據
* @param sql
* @return
* @throws
*/
//region 查詢,又多少條行數
public static int hasrows(String sql) {
int result = 0;

try {
Connection conn = getSQLConnection();

Statement stmt = conn.createStatement();//
ResultSet ss =stmt.executeQuery(sql);
if (!ss.next()) {
result=0;
} else {
result=1;
}
ss.close();
stmt.close();
conn.close();
} catch (SQLException e) {
String res = "查詢數據異常" + e.getMessage();
return -1;
} catch (Exception e) {
String res = "無網絡";
return -1;

}
return result;
}
//endregion


//region 傳入sql,返回轉換成List(查詢)
public static <T> List QueryT(String sql,T t) {
List result = new ArrayList();

ResultSet rs = null;
try {
Connection conn = getSQLConnection();

Statement stmt = conn.createStatement();//
rs = stmt.executeQuery(sql);
result = util(t,rs);

rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
// String res = "查詢數據異常" + e.getMessage();
// e.printStackTrace();
String res = "nodate";
result.add(res);
return result;
} catch (Exception e) {
String res = "無網絡";
result.add(res);
return result;
}

return result;
}




/**
* ResultSet轉List<T>
* @param t
* @param rs
* @return
* @throws
*/
public static <T> List util(T t, ResultSet rs) throws Exception {
// 創建一個對應的空的泛型集合
List<T> list = new ArrayList<T>();
List ALL=new ArrayList();
// 反射出類類型(方便后續做操作)
Class c = t.getClass();
// 獲得該類所有自己聲明的字段,不問訪問權限.所有。所有。所有
Field[] fs = c.getDeclaredFields();
int count=0;
// 大家熟悉的操作,不用多說
ALL.add("nodate");
int ros=rs.getRow();
if (rs != null) {
while (rs.next()) {
count++;
if(count==1){
ALL.set(0,"ok");
}
// 創建實例
t = (T) c.newInstance();
// 賦值
for (int i = 0; i < fs.length; i++) {
/*
* fs[i].getName():獲得字段名
*
* f:獲得的字段信息
*/
Field f = t.getClass().getDeclaredField(fs[i].getName());
// 參數true 可跨越訪問權限進行操作
f.setAccessible(true);
/*
* f.getType().getName():獲得字段類型的名字
*/
// 判斷其類型進行賦值操作
if (f.getType().getName().equals(String.class.getName())) {
f.set(t, rs.getString(fs[i].getName()));
} else if (f.getType().getName().equals(int.class.getName())) {
f.set(t, rs.getInt(fs[i].getName()));
}
}

list.add(t);
}
}

ALL.add((list));
// 返回結果
return ALL;
}

//endregion
/**
* List<Map<String, Object>>轉List<T>
* @param list
* @param clazz
* @return
* @throws
*/

public static <T> List<T> castMapToBean(List<Map<String, Object>> list, Class<T> clazz) throws Exception {
if(list == null || list.size()==0) {
return null;
}
List<T> tList = new ArrayList<T>();
// 獲取類中聲明的所有字段
Field[] fields = clazz.getDeclaredFields();

T t;
for(Map<String, Object> map : list) {
// 每次都先初始化一遍,然后再設置值
t = clazz.newInstance();
for(Field field : fields) {
// 把序列化的字段去除掉
if(!"serialVersionUID".equals(field.getName())){
// 由於Field都是私有屬性,所有需要允許修改
field.setAccessible(true);

// 設置值, 類型要和vo對應好,不然會報類型轉換錯誤
field.set(t, map.get(field.getName()));
}
}
tList.add(t);
}

return tList;
}



/**
* 返回的List的[1]數據時List<T>
* @param sql
* @return
* @throws
*/



//
/**
* 過濾非法字段
* @param str
* @return
* @throws
*/
public static boolean sql_inj(String str) {

String inj_str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+|,";

String inj_stra[] = split(inj_str, "|");

for (int i = 0; i < inj_stra.length; i++) {

if (str.indexOf(inj_stra[i]) >= 0) {
return true;
}

}

return false;

}

public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();

Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
continue;
}

field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
}
}


3、根據上個工具類,構造專屬自己專屬工具類(。。。。。。)

public class SqlDto {

private String sql;

public SqlDto() {
}

public SqlDto(String sql) {
this.sql = sql;
}

public String getSql() {
return sql;
}

public void setSql(String sql) {
this.sql = sql;
}

@Override
public String toString() {
return "SqlDto{" +
"sql='" + sql + '\'' +
'}';
}
}



import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DbHelper {

//region 常規操作數據庫
//批量執行sql語句,都執行成功,返回ok,存在失敗語句,返回no
public static String listsql(List<SqlDto> sql) {

String res = "";
int count = 0;
String tip = "";
for (int i = 0; i < sql.size(); i++) {

List ret = DBUtil.exesql(sql.get(i).getSql());
String dd = ret.get(0).toString();
String status = dd;

List<Production> p = new ArrayList<Production>();

switch (dd) {
case "ok":
count++;
break;
case "nodate": //更新sql語句失敗
break;
case "無網絡": //脫機操作
//脫機操作
break;
default: //其他異常
break;
}

}

if (count > 0) {

res = "ok";
} else {

res = "no";
}

return res ;
}

//單獨執行sql語句 執行成功 返回ok ,執行失敗,返回no
public static String ExcuteSql(String sql) {

String res = "";

int i = DBUtil.exesqlint(sql);

if (i > 0) {
//插入成功
res = "ok";

} else {
res = "no";
}

return res;

}


// 入參數 sql + 需要查詢的字段構造一個對象
//返回 list<查詢對象> 集合
public static <T> List QueryData(String sql, T t) {

List list = DBUtil.QueryT(sql, t);
String dd = list.get(0).toString();
String status = dd;
String tip = "";
List<T> t2 = new ArrayList<T>();
switch (dd) {
case "ok":
t2 = (List<T>) list.get(1);
break;
case "nodate": //沒有獲取到數據
break;
case "無網絡": //脫機操作
break;
default: //其他異常

}
return t2;
}
//endregion



//region 調用數據庫中的存儲過程
/**
* 存儲過程返回的是一個行數據,構造一個接收對象,有無該條數據
* @param tm,worker,inputer,T
* @return List<T>
* @throws
*/
public static List<接收對象> 存儲過程名字(傳入的參數列表)
{

List<接收對象> list = new ArrayList<>();
try {

Connection conn =DBUtil.getSQLConnection();
String call = "{call SQLSEVER存儲過程( 有幾個參數,幾個問號)}";
CallableStatement callStatement = conn.prepareCall(call);
callStatement.setString("參數一的名字", 參數一的值);
callStatement.setString("參數二的名字", 參數二的值);

ResultSet set = callStatement.executeQuery();
/* callStatement.get
ResultSet set = callStatement.getResultSet();*/


//List<Map>
List list1 = new ArrayList();
list1 = DBUtil.convertList(set);

Map<String,Object> map = new HashMap<>();


if(list1.get(0).toString().equals("ok")){
ArrayList list2 = (ArrayList) list1.get(1);
for (int i = 0 ; i < list2.size() ; i ++)
{
map = (Map<String,Object>)list2.get(i);
對象 實例 = new 對象();

實例.set參數名(map.get("參數名").toString());
。。。。。。
list.add(p);
}
}

callStatement.close();
conn.close();

} catch (SQLException e) {
String res = "執行數據異常" + e.getMessage();
return list;
} catch (Exception e) {
e.printStackTrace();
}
return list;

}
//endregion


//獲取遠程服務器時間
public static Date getSystemTime(){
Map<String,Object> map = new HashMap<>();
String sql = "select GETDATE() as datetime";
List list = DBUtil.Query(sql);
String time = "";
if(list.size() > 0){
map = (Map<String,Object>)list.get(0);
time = map.get("datetime").toString();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
try {
date = sdf.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}

return date;

}




//獲取遠程服務器小時
public static int getRemoteSystemHour(){

Hour hour = new Hour();
String sql = "SELECT DateName(hour,GetDate()) as hour";
List<Hour> list = DbHelper.QueryData(sql,hour);
String h = "";
if(list.size() > 0){
h = list.get(0).getHour();
}
int hour2 = Integer.parseInt(h);

return hour2;


}



}


4:實例調用
(1)批量調用(增、刪、改SQL)
List<SqlDto> sql_list = new ArrayList<>();
for (int i = 0; i < arr1.size(); i++) {
String sql = arr1.get(i).toString();
SqlDto sqlDto = new SqlDto();
sqlDto.setSql(sql);
sql_list.add(sqlDto);
}
其中數組arr1中存儲的是sql語句的集合
String res = DbHelper.listsql(sql_list);      //去執行
if (res.equals("ok")) {
//批量SQL語句執行成功
}

(2)查詢SQL

查詢對象:是SQL語句返回列的列名構造的查詢對象,構造時無參構造函數+getset方法
查詢對象 實例  = new 查詢對象
List<查詢對象> 對象集合= new ArrayList<>();
對象集合= DbHelper.QueryData(sql語句,實例);
遍歷對象集合,可以查詢到相關數據。

(3)執行SQLSEVER存儲過程(有返回值得存儲過程)
List<接受對象> 接受對象集合 =  DbHelper.自己寫的存儲過程函數(入參列表);
遍歷對象集合,可獲取到存儲過程的返回值










免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM