简体   繁体   中英

Sql Query statement in operator

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]

result of selectAuther() is [john]

i know that i can do this 2 query by 1 query but i will save the selectAuther() in my project when user login to use it multiple time without load to database

i know that i can write it by this way

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
}
}

but i don't need this way

If you want to use Groovy, why not use the Groovy Sql classes and leverage all the benefits that groovy gets you?

I believe this is an exact replacement for your original code...

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
  }
}

A possible solution using string utils from Apache Commons Lang:

import org.apache.commons.lang.StringUtils;

String list2string =  StringUtils.join(autherName, ", ");  

rs = stmt.executeQuery(
            "SELECT name FROM book WHERE authername in (" + 
            list2string + 
            ")"
           )

Remember that each item on the list must be quote enclosed: 'pere', 'joan', ...

If you don't want to import apache string utilities, you should write join function. I copy here a sample from code.hammerpig.com :

import java.util.*;

...

public static String Join(String[] s, String delimiter)
{
    return Join(Lists.CreateStringList(s), delimiter);
}

public static String Join(ArrayList<String> coll, String delimiter)
{
    if (coll.isEmpty())
    return "";

    StringBuilder sb = new StringBuilder();

    for (String x : coll)
       sb.append(x + delimiter);

    sb.delete(sb.length()-delimiter.length(), sb.length());

    return sb.toString();
}

It appears to be a syntax issue, the implicit List.toString() that takes place when placing "autherName" in the query wraps the members with a rectangular brackets "[" while the IN predicate expects parentheses "(".

So the solution in this case should be something like:

...
rs = stmt.executeQuery("SELECT name FROM book WHERE authername in " +
wrapWithParentheses(autherName) + "")
...

And the formatting function:

def String wrapWithParentheses(List list){
    if (list !=null){
        StringBuilder result = new StringBuilder().append("(");
        for (Object o : list){
           result.append(o.toString()).append(",");
        }
    result.append(")");
    }
}

You have two problems, you are not quoting the names, and you have a syntax error in your SQL.

What you want to end up with is something like:

SELECT name FROM book WHERE authername in ('john')

john needs to be surrounded by quotes and the entire in clause needs to be surrounded by ().

def selectbook(List autherName){
    def nameList = []

    String listStr = ""
    autherName.each{
        if (listStr.length() > 0){
            listStr +=","
        }
        listStr +="'${it}'"
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM