java read table and return dynamic
import java.net.*;import java.io.*;import java.util.HashMap;
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;
import java.sql.SQLException;import java.sql.Statement;
public class tableRead2
{
public static void main(String[] args)
{
String r=getSQLData("invhead","custCode,date,invoice, duedate, amount","custCode","1234","I,D,D,D,D");
System.out.println(r);
}
public static String getSQLData(String table,String fields,String key,String value,String format)
{
String result="";
try {
ResultSet rs = null;
Connection con = null;
Statement stmt = null;
String formats[]=format.split(",");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.
getConnection("jdbc:mysql://localhost/Database?useUnicode=true&characterEncoding=UTF8","UserID", "UserPassword"); //jdbc connection setting
stmt = con.createStatement();
String sqlString="select "+fields+" from "+table+" where "+key +" = "+value +" ;";
rs = stmt.executeQuery(sqlString);
int iRecno=0;
String rD=""; // RowDelimiter
while (rs.next()){
result=result+rD+"[";
String fD=""; // fD=fieldDelimiter
for (int j=1; j<=formats.length; j++){
if (formats[j-1].equals("I")){
result=result+fD+Integer.toString(rs.getInt(j));}
if (formats[j-1].equals("D")){
result=result+fD+Double.toString(rs.getDouble(j));}
if (formats[j-1].equals("L")){
result=result+fD+Long.toString(rs.getLong(j));}
if (formats[j-1].equals("S")){
result=result+fD+rs.getString(j);}
fD=",";
}
result=result+"]";
rD=",\n";
++iRecno;
}
result="{'result':["+result+"]}";
//result="(["+result+"])";
con.close();
} catch (Exception e) {e.printStackTrace();}
return result;
}
}
沒有留言:
張貼留言