gpt4 book ai didi

java - 运算符中的sql查询语句

转载 作者:行者123 更新时间:2023-11-29 04:27:52 24 4
gpt4 key购买 nike

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class test{

def selectAuther(){
def nameList = []

con = DriverManager.getConnection("url", "username", "password")
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT name FROM auther");
while (rs.next()) {
nameList.add(rs.getString(1));
}
con.close();
return nameList;
}

def selectbook(List autherName){
def nameList = []
con = DriverManager.getConnection("url", "username", "password")
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT name FROM book WHERE authername in " + autherName + "")
while (rs.next()) {
nameList.add(rs.getString(1));
}
con.close();
return nameList
}
}
where autherName is a parameter = selectAuther()

异常:

You have an error in your SQL syntax; check the manual that corresponds to your 
MySQL server version for the right syntax to use near '[john]

selectAuther() 的结果是 [john]

我知道我可以通过 1 个查询执行这 2 个查询,但是当用户登录多次使用它而不加载到数据库时,我会将 selectAuther() 保存在我的项目中

我知道我可以这样写

def selectbook(){
def nameList = []
con = DriverManager.getConnection("url", "username", "password")
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT name FROM book WHERE authername in (SELECT name FROM auther))
while (rs.next()) {
nameList.add(rs.getString(1));
}
con.close();
return nameList
}
}

但我不需要这样

最佳答案

如果您想使用 Groovy,为什么不使用 Groovy Sql 类并利用 groovy 为您带来的所有好处呢?

我相信这完全可以替代您的原始代码...

import groovy.sql.Sql

class Test{
List selectAuther( sql ){
List nameList = []
sql.eachRow( 'SELECT name FROM auther ' ) {
nameList << it.name
}
nameList
}

List selectbook(List autherName){
def sql = Sql.newInstance( 'url', 'username', 'password', 'driver' )
List autherName = selectAuther( sql )
List nameList = []
sql.eachRow( "SELECT name FROM book WHERE authername in ('" + autherName.join( "','" ) + "')" ) {
nameList << it.name
}
nameList
}
}

关于java - 运算符中的sql查询语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8008306/

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