1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
package
com.json;
import
java.sql.*;
import
java.lang.reflect.*;
public
class
JsonConvert {
//设置数据库连接属性
Connection connection=
null
;
String driverName =
"com.mysql.jdbc.Driver"
;
String url =
"jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gb2312"
;
String user =
"root"
;
String password =
"000000"
;
String table=
"student"
;
int
count;
public
static
void
main(String[] args) {
// TODO Auto-generated method stub
JsonConvert jv=
new
JsonConvert();
//jv.getResult();
System.out.println(jv.TableToJson());
}
public
String TableToJson(){
//把表记录转换成Json格式
StringBuffer resultJson=
new
StringBuffer();
resultJson.append(
"{"
+
this
.table+
":"
);
resultJson.append(
"{record:["
);
ResultSet rs=
this
.getResult();
try
{
int
i=
0
;
while
(rs.next()){
resultJson.append(
"{"
);
for
(
int
j=
0
;j
//System.out.println(rs.getMetaData().getColumnName(j+1));
String cn=rs.getString(j+
1
);
resultJson.append(rs.getMetaData().getColumnName(j+
1
)+
":"
+cn);
if
(j
resultJson.append(
","
);
}
if
(i==(count-
1
))
resultJson.append(
"}"
);
else
resultJson.append(
"},"
);
i++;
}
resultJson.append(
"]}}"
);
connection.close();
}
catch
(Exception se){
se.printStackTrace();
}
return
resultJson.toString();
}
private
ResultSet getResult(){
//获取表记录
ResultSet rs=
null
;
try
{
Class.forName(driverName);
this
.connection = DriverManager.getConnection(url,user,password);
String statement=
"select * from student "
;
PreparedStatement ps=
this
.connection.prepareStatement(statement);
rs=ps.executeQuery();
ps=
this
.connection.prepareStatement(
"select count(*) as cc from student"
);
ResultSet rs1=ps.executeQuery();
rs1.next();
count=rs1.getInt(
"cc"
);
}
catch
(ClassNotFoundException noclass){
noclass.printStackTrace();
}
catch
(SQLException se){
se.printStackTrace();
}
catch
(Exception e){
e.printStackTrace();
}
return
rs;
}
}
|