目前在Thingwrox平台下基于Composer模式下进行Service的开发时,当我们要去操作数据库时,是通过在创建Thing时继承了包含了SQL语言开发环境下的ThingTemplate,在实际开发中这种方式带来诸多的不便,首先对不同的数据库进行操作时要建立不同的Thing集成不同的数据库configuration,进行不同的数据库连接;其次,每一次访问数据库都需要建立一个新的service进行操作,然后再在JS环境下调用这个Service进行对应的数据处理,一方面非业务逻辑类的Service大幅增加,加大service的管理幅度,其次在JS环境下代码的可读性比较差,比如想要看具体的操作代码必须切回相应的sql语言对应的Service,操作麻烦;第三,操作不同种类的数据库,如microsoft SQL、MySQL、Oracle等等需要继承不同的ThingTemplate进行操作,如果可以在一个ThingTemplate中完成不同种数据库的操作,将统一数据层的操作驱动,这也有较大的便利和管理;最后,如果需要在一个service中访问两个数据库,目前的操作方法要建立两个Thing继承两个ThingTemplate,既浪费了Thing的数量,操作、调试也要来回切换。
基于上述目前操作数据库诸多不便利,开发了一个全新的数据库操作ThingTemplate,可以解决上述的问题:
(1)可在JS环境下直接调用相应的service(Queuery、ExcuteUpdate)进行数据库的操作;
(2)具备同时操作两个数据库的configuration;
(3)集成常用的集中数据库操作驱动(初期支持微软SQL,后期更新MySQL、Oracle等)。
本文仅用于技术上的可行性讨论,从实际解耦合的角度来看,还是推荐采用MVC的模式,即DAO最好还是直接放在后端进行数据的处理,js负责业务的调用并由Mashap前端的最终调用。
1、创建SQL操作类:
package sqlconnectTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import org.json.JSONException;
import org.json.JSONObject;
import com.thingworx.metadata.FieldDefinition;
import com.thingworx.types.BaseTypes;
import com.thingworx.types.InfoTable;
public class sqlConnect {
public InfoTable connectDB(String url,String user,String password,String str,String sqlServerDriver) throws Exception{
//连接数据库
Connection con=null;
PreparedStatement pst=null;
ResultSet rst=null;
ResultSetMetaData rsm=null;
InfoTable info=new InfoTable();
try{
Class.forName(sqlServerDriver);
con=DriverManager.getConnection(url,user,password);
pst=con.prepareStatement(str);
rst=pst.executeQuery();
rsm=rst.getMetaData();
//创建INFOTABLE的列名
for(int i=1;i<=rsm.getColumnCount();i++){
String colName=rsm.getColumnName(i);
String colType=rsm.getColumnTypeName(i);
FieldDefinition field=getField(colName,colType);
info.addField(field);
}
//写进INFOTABLE各行值
while(rst.next()){
JSONObject json=new JSONObject();
for(int i=1;i<=rsm.getColumnCount();i++){
String colName=rsm.getColumnName(i);
json.put(colName, rst.getObject(i));
}
info.AddRow(json);
}
con.close();
pst.close();
rst.close();
}catch(Exception ex){
String excep=ex.toString();
FieldDefinition fieldEx=new FieldDefinition("Exception", BaseTypes.STRING);
info.addField(fieldEx);
JSONObject jsonEx=new JSONObject();
jsonEx.put("Exception",excep);
info.AddRow(jsonEx);
}
finally{
try{
if(con!=null){
con.close();
}
if(pst!=null){
pst.close();
}
if(rst!=null){
rst.close();}
}catch