对 Java 字符串的 SQL 查询

Posted

技术标签:

【中文标题】对 Java 字符串的 SQL 查询【英文标题】:SQL query to Java String 【发布时间】:2021-05-14 21:01:33 【问题描述】:

我有一个简单的问题,但我找不到正确的方法。当我们通过 Java 使用 SQL 查询时,我们通常在 JTable 中打印结果,我怀疑这是 ¿ 有没有办法将该查询转换为 Java 字符串?

示例:我做一个查询 statement.executeQuery("SELECT Tiempo_elaboracion FROM catalogo_arreglos WHERE Id_arreglo='"+id_arre+"'");

结果是 00:07:00 ¿如何将该结果保存到 Java 字符串中?

【问题讨论】:

【参考方案1】:

结果实际上是一个ResultSet,它包含所有匹配的行(可能只有一个)和所有选定的列(可能只有一个)。

一些序列如

 if (!rs.first())  ... error no first row ... 
 String str = rs.getString("Tiempo_elaboracion");

应该这样做。但是不要把这当成福音,我只是偷看了documentation。以它为起点。

【讨论】:

【参考方案2】:

我找到了一个额外的解决方案来补充,我为所有将来需要帮助的人发帖。

ResultSet myRS;
PreparedStatement myQuery
//Under this line "con" is the name of my connection//
myQuery = con.prepareStatement(SELECT value FROM table WHERE condition)
myRS = myQuery.executeQuery();
//The purpose is the save the value of the query into the String called "time"
if(myRS.next())
String time = myRS.getString(1);
//The next line only print the String "time" for corroborate the procces//
System.out.println(""+time);

【讨论】:

以上是关于对 Java 字符串的 SQL 查询的主要内容,如果未能解决你的问题,请参考以下文章

将 SQL 查询结果转换为字符串数组

java用sql语句查询某一时间段内的记录

java.sql.SQLException:SQL 字符串不是 glassfish 服务器中的查询

SQL2000里面字符串排序

我可以在不创建实体类的情况下对大型 sql 使用休眠命名查询吗?

java--sql模糊查询(字符串拆分与拼接)