//需要两个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";
//这里我的数据库名字是Person,改成你自己的数据库名
String url = "jdbc:mysql://localhost:3306/Person";
String user = "root";
String pwd = "root";
try {
Class.forName(driver);
Connection con = DriverManager.getConnection(url,user,pwd);
Statement stet = con.createStatement();
//我的数据库Person中的表student,改成你自己的表
String sql = "select * from student";
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数据:[{"sno":"001","name":"lisi","age":"21"},{"sno":"002","name":"zhangsan","age":"20"},{"sno":"003","name":"wangwu","age":"22"},{"sno":"004","name":"fdx","age":"18","email":"
[email protected]"}]
//下载两个jar包,导入,(我是在eclipse中运行的----java代码)把我红色标明的注释改一下。就可以运行了。