//需要两个jar包,一个连接接数据库(mysql-connection-java-5.1.7-bin.jar),一个关于json(json.jar),网上一搜就找到了,
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import org.json.JSONArray;
import org.json.JSONObject;
public class Mysql {
public static void main(String[] args) {
String driver = "com.MySQL.jdbc.Driver";
//这里我的数据库名字是Test,改成你自己的数据库名
String url = "jdbc:mysql://localhost:3306/Test";
String user = "root";
String pwd = "root";
try {
Class.forName(driver);
Connection con = DriverManager.getConnection(url,user,pwd);
Statement stet = con.createStatement();
//我的数据库Test中的表tstudent,改成你自己的表
String sql = "select * from tstudent";
ResultSet rs = stet.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int columnCount= metaData.getColumnCount();
JSONArray array = new JSONArray();
while(rs.next()){
JSONObject jsonObj = new JSONObject();
for(int i = 1; i <= columnCount;i++)
{
String columnName = metaData.getColumnLabel(i);
String value =rs.getString(columnName);
jsonObj.put(columnName, value);
}
array.put(jsonObj);
}
System.out.println("转换JSON数据:");
System.out.println(array.toString());
con.close();
} catch (Exception e) {
e.printStackTrace();// TODO: handle exception
}
}
}
// 结果是: 转换JSON数据:[{"tsno":"001","tname":"lisi","tage":"21"},{"tsno":"002","tname":"zhangsan","tage":"20"},{"tsno":"003","tname":"wangwu","tage":"22"},{"tsno":"004","tname":"fdx","tage":"18","temail":"
[email protected]"}]
//下载两个jar包,导入,(我是在Myeclipse中运行的----java代码)把我红色标明的注释改一下。就可以运行了。