论坛首页 Java企业应用论坛

Xfire 实现.net 平台PDA数据交互

浏览 2094 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-02-27   最后修改:2009-02-27
SOA
做了2天,终于接近尾声了。期间遇到很多问题。下面分享一下 


1、数据查询以xml文件格式的字符串进行数据交互,遍历结果集部分代码如下:
  /**   
    *  @param  ResultSet  rs输入的结果集   
     *  @return  String  返回XML串   
     *  @exception  SQLException   
    */   
    public String GetXML(ResultSet rs) throws SQLException, IOException { 
final StringBuffer buffer = new StringBuffer(1024 * 4); 
buffer.append("<?xml  version=\"1.0\"  encoding=\"UTF-8\"?>\n"); // XML的头部信息 
buffer.append("<RowSet>\n"); 
buffer.append("\t" + GetTableXML(rs, "Table") + "\n"); 
buffer.append("</RowSet>"); 
rs.close(); 
return buffer.toString(); 
}


  /**   
    *  @param  ResultSet  rs输入的结果集   
    *  @return  String  返回XML串   
    */
  
 public String GetTableXML( ResultSet rs,String TableName) throws SQLException, IOException {
    	String xml="";
        final StringBuffer buffer = new StringBuffer(1024 * 4);
       
        if (rs!=null)
        {
        	 ResultSetMetaData rsmd = rs.getMetaData();  //得到结果集的定义结构  
     		int colCount = rsmd.getColumnCount(); // 得到列的总数
     		for (int id = 0; rs.next(); id++) {
     			buffer.append("\t<" + TableName + ">\n");
     			for (int i = 1; i <= colCount; i++) {
     				int type =rsmd.getColumnType(i); // 获取字段类型
     				buffer.append("\t\t<" + rsmd.getColumnName(i) + ">");
     				buffer.append(getValue(rs, i, type));
     				buffer.append("</" + rsmd.getColumnName(i) + ">\n");
     			}
     			buffer.append("\t</" + TableName + ">\n");
     			xml=buffer.toString();
     		}        
             rs.close();
        }
        else if (rs == null || !rs.next())  {
        	System.out.println("结果集为空");
        }
        return xml;
    }
/**   
    *  This  method  gets  the  value  of  the  specified  column   
    *  通用的读取结果集某一列的值并转化为String表达   
    *  @param  ResultSet  rs  输入的纪录集   
    *  @param  int  colNum  第几列   
    *  @param  int  type  数据类型   
    */
//重点
     private String getValue( ResultSet rs, int colNum, int type) throws SQLException, IOException {
    	String xml="";
        switch (type) 
        {
            case Types.ARRAY:
            case Types.BLOB:
            case Types.CLOB:
            case Types.DISTINCT:
            case Types.LONGVARBINARY:
            case Types.VARBINARY:
            case Types.BINARY:
            case Types.REF:
            case Types.STRUCT:
               BufferedInputStream is = null;
            	Blob blob=(Blob) rs.getObject(colNum);
                is = new BufferedInputStream(blob.getBinaryStream());
                byte[] bytes = new byte[(int) blob.length()];
                int offset = 0;
                int read = 0;
                int len = bytes.length;
                while (offset < len&& (read = is.read(bytes, offset, len - offset)) >= 0) {
                	offset += read;
                }
                BASE64Encoder enc=new BASE64Encoder();
                xml=enc.encode(bytes);
                is.close();
            	is = null;
                break;
            default: {
                Object value = rs.getObject(colNum);
                if (rs.wasNull() || (value == null)) {
                    return ("");
                } else {
                    xml=value.toString();
                }
            }
        }
        return xml;
    }

2、web service 接口类
public class OperateImp implements Operate {

	// 执行增删改操作
	public int ExecuteNonQuery(String executeNoQuery) {
		int i = 0;
		try {
			DataBase db = new DataBase();
			Connection con = db.setConnection();
			Statement stmt = con.createStatement();
			Statement stmtUpdate = con.createStatement();
			i = stmtUpdate.executeUpdate(executeNoQuery);
			db.cleanup();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return i;
	}

	// 查询某结果集首条记录的首字段
	public Object ExecuteScalar(String executeScalar) {
		Object scalar = "";
		try {
			DataBase db = new DataBase();
			Connection con = db.setConnection();
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery(executeScalar);
			while (rs.next()) {
				scalar = rs.getString(1);
			}
			db.cleanup();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return scalar;
	}

	public String ExecuteDataset(String executeDataset) {
		String result = "";
		try {
			DataBase db = new DataBase();
			Connection con = db.setConnection();
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery(executeDataset);
			XMLWriter xml = new XMLWriter();
			result = xml.GetXML(rs);
			db.cleanup();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	// 图片入库
	public boolean insertXQPIC(String insertXQPIC,byte [] bytes,String pictureId) {
		boolean boo=false;
		
		OutputStream outStream=null;
		try
		{
			DataBase db = new DataBase();
			Connection con = db.setConnection();
			BlobToString bts=new BlobToString();
			con.setAutoCommit(false); // 事物由程序员操作
			Statement st = con.createStatement();
			
		    //插入一个空对象empty_blob()
			st.executeQuery(insertXQPIC);
			//通过pictureId查询刚刚传入的数据
			ResultSet rs = st.executeQuery("select pic from ZKR_XQPIC where picid='"+pictureId+"'  for update");
			if (rs.next()) {
		        BLOB blob = (BLOB) rs.getBlob("pic");
		        outStream = blob.getBinaryOutputStream();
		        //data是传入的byte数组,定义:byte[] data
		        outStream.write(bytes, 0, bytes.length);
		        boo=true;
			}
			 outStream.flush();
			 outStream.close();
			 con.commit();
			 con.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return boo;
	}

	private byte[] blobToBytes(Blob blob) {
		BufferedInputStream is = null;
		try {
			is = new BufferedInputStream(blob.getBinaryStream());
			byte[] bytes = new byte[(int) blob.length()];
			int len = bytes.length;
			int offset = 0;
			int read = 0;
			while (offset < len&& (read = is.read(bytes, offset, len - offset)) >= 0) {
				offset += read;
			}
			return bytes;
		} catch (Exception e) {
			return null;
		} finally {
			try {
				is.close();
				is = null;
			} catch (IOException e) {
				return null;
			}
		}
	}
}


3、客户端调用
public class ClientMain {
	public static void main(String agp[]) {
		Service serviceModel = new ObjectServiceFactory().create(Operate.class);

		// Create a proxy for the deployed service
		XFire xfire = XFireFactory.newInstance().getXFire();
		XFireProxyFactory factory = new XFireProxyFactory(xfire);
		String serviceUrl = "http://localhost:8080/PDA/services/OperateService";
		Operate client = null;
		try 
		{
			client = (Operate) factory.create(serviceModel, serviceUrl);
		} 
		catch (MalformedURLException e) {
		}
		int serviceResponse =0;
		String  rs=null;
		String scalar=null;
		try {
//			//增删改操作
//			String sql="insert into st_dayev_r values('2','2001-01-01 00:00:00','0','0','222')";
//			String sql="insert into ZKR_XQPIC values('00004',empty_blob(),'20081026','','')";
//			serviceResponse = client.ExecuteNonQuery(sql);
//			System.out.println(serviceResponse);
			
			//查询操作
//			String sqlQuery="select * from ZKR_XQPIC where picid='00004' ";
//			rs=client.ExecuteDataset(sqlQuery);
//			System.out.println(rs);
//			//查询单个字段
//			String sqlscalar="select * from zkr_sfya where yaid='2009010402' ";
//			scalar=(String) client.ExecuteScalar(sqlscalar);
//			System.out.println(scalar);
			
			//插入图片
			String insertXQPIC="insert into ZKR_XQPIC (picid,pic,refid) values('012',empty_blob(),'20081026')";
			byte []bytes=new byte[10];
			String pictureId="012";
			boolean boo=client.insertXQPIC(insertXQPIC, bytes,pictureId);
			System.out.println(boo);


		} catch (Exception e) {
			System.out.println("出错了");
			e.printStackTrace();
		}
	}
}
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics