gpt4 book ai didi

java - SQL Server 2008 - 如何同时获取列名和值?

转载 作者:行者123 更新时间:2023-12-01 19:19:55 25 4
gpt4 key购买 nike

我不确定这是否可能..

我使用的是 SQL Server 2008 和 Java。

我有一张 table

--------------
| users |
--------------
| name |
| address |
| password |
|____________|

然后我这样做:

SELECT name, address, password FROM users;

我从每一列中获取了所有值。

但是如果我也想获取列名称怎么办?

当查询结果返回时,我想知道查询的是哪一列。

如何将值和列放在一起?是否可以在不更改使用 Java 的查询的情况下实现?

代码

em = EmProvider.getInstance().getEntityManagerFactory().createEntityManager();
Query query = em.createNativeQuery("SELECT name, address, password, birthday FROM users");
//query result is stored in list consists of object array
List<Object[]> out = query.getResultList();

//so result is like this
List<
[john, 1st ave, 1234, 12/12/2010]
[mike, 2st ave, 1111, 12/11/2011]
>

//now I create JSON
{name:john, address:1st ave, birthday....}

但是查询可能会发生变化,因此当我构造 JSON 时,我不想硬编码“名称”或“地址”。

最佳答案

列名称来自 ResultSetMetaData。

例如:

String sql = "Select * from Activity";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();

// Get column names

for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}

// Get row data

while (rs.next())
{
Vector row = new Vector(columns);

for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}

data.addElement( row );
}

关于java - SQL Server 2008 - 如何同时获取列名和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4779139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com