当前位置:网站首页>根据SQL语句查询出的结果集,将其封装为json
根据SQL语句查询出的结果集,将其封装为json
2022-04-23 05:45:00 【dawnsun001】
根据SQL语句查询出的结果集,将其封装为json
例如:
1.select id,username,password,sex from user where id=11
{id:1,username:'jibs',password:'ssdfsdfsfwe',sex:'男'}
/**
* 通过sql查询结果封装成json
* <br />
* <p>Example:</p>
* <code>String sql = "select id,username,password,sex from user where id=12";</code>
* @param sql 查询SQL
* @return {"id":"1","username":"jibs","password":"ssdfsdfsfwe","sex":"男"}
*/
代码:
package com.dawnsun.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestSql2Json {
public static void main(String args[]) throws JSONException{
Connection conn = null;
Statement stat = null;
String url = "jdbc:mysql://localhost:3306/databasename";
String sql ="select * from student";
ResultSet rs = null;
JSONArray array = null;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,"username","password");
stat = conn.createStatement();
rs = stat.executeQuery(sql);
// json数组
array = new JSONArray();
// 获取列数
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// 遍历ResultSet中的每条数据
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);
}
//通过key获取每个对应value
for(int j=0;j<array.length();j++){
for(int i=1;i<columnCount;i++){
String columnName =metaData.getColumnLabel(i);
JSONObject resultObj = array.optJSONObject(j);
//获取数据项
String value = resultObj.getString(columnName);
logger.info(value);
}
}
//测试json数据的条数
// int ii = array.length();
rs.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
return array.toString();
}
版权声明
本文为[dawnsun001]所创,转载请带上原文链接,感谢
https://blog.csdn.net/dawnsun2013/article/details/19625619
边栏推荐
- [leetcode217] there are duplicate elements
- Programming record - picture rotation function SciPy ndimage. Simple use and effect observation of rotate()
- MySQL table constraints and table design
- GNU EFI header file
- C # Foundation
- Three ways to create threads
- scikit-learn sklearn 0.18 官方文档中文版
- Busybox initrd and initialization process
- Storing inherited knowledge in cloud computing
- C3p0 database connection pool usage
猜你喜欢
GDAL+OGR学习
[leetcode 54] spiral matrix
How SYSTEMd uses / etc / init D script
Algèbre linéaire chapitre 1 - déterminants
Algèbre linéaire chapitre 2 - matrice et son fonctionnement
The bottom implementation principle of thread - static agent mode
Techniques et principes de détection
Robocode教程3——Robo机器剖析
Export of data
Reading of denoising papers - [cvpr2022] blind2blind: self supervised image denoising with visible blind spots
随机推荐
Use of multithreaded executors
How SYSTEMd uses / etc / init D script
Problems and solutions of database migration
[transfer] MySQL: how many rows of data can InnoDB store in a B + tree?
Doomsday (simple computational geometry)
C3p0 database connection pool usage
POI and easyexcel exercises
Protected (members modified by protected are visible to this package and its subclasses)
word排版遇到的格式问题
Programming record - picture rotation function SciPy ndimage. Simple use and effect observation of rotate()
Import of data
Collections multiple parameter sorting
11.a==b?
Preparedstatement prevents SQL injection
20 excellent plug-ins recommended by idea
12. Monkeys climb mountains
The problem that the page will refresh automatically after clicking the submit button on the form is solved
MySQL advanced query
The bottom implementation principle of thread - static agent mode
H. Are You Safe? Convex hull naked problem