简体   繁体   中英

how to insert variable into SQL query

i have test scripts, the productId is stored in text file which I can use the read method to retrieve it.

import static org.assertj.core.api.Assertions.*
import groovy.json.JsonOutput as JsonOutput
import groovy.json.JsonSlurper as JsonSlurper
import internal.GlobalVariable as GlobalVariable
import internal.GlobalVariable
import com.kms.katalon.core.configuration.RunConfiguration
import java.sql.*
import java.io.File

//Read productId
def productId = new File(RunConfiguration.getProjectDir() + "/Data Files/productId.txt")

//SQL statement
String dbQuery2 = /SELECT * FROM db.table1 where productId= @productId order by lastmodificationdateutc desc/

how do i use the @ as variable and replace it with the "productId.text" ?

i have tried below codes but it does not work please correct me if this method can be used?

    String dbQuery2 = "SELECT * FROM db.table1 where productId = ?"
    def productId = new File(RunConfiguration.getProjectDir() + "/Data Files/productId.txt")
    PreparedStatement stmt = con.prepareStatement(dbQuery2)
    stmt.setString(1, productId.text)
    ResultSet resultSet = preparedStatement.executeQuery()

ResultSet resultSet = stmt.executeQuery()

//Connect to PostgresSQL, global variable is stored at profile
List resultSet = CustomKeywords.'test.database.getPostgresSQLResults'(GlobalVariable.dbConnString2 , GlobalVariable.dbUsername2 , GlobalVariable.dbPassword2 ,GlobalVariable.dbDriver2 ,dbQuery2 )

below is codes which is working without preparedstatement

the connection string in the script

//to connect PostgresSQL server
    @Keyword
    def List getPostgresSQLResults (String dbConnString2 , String dbUsername2 , String dbPassword2 , String dbDriver2 , String dbQuery2){

        Sql sql = Sql.newInstance(dbConnString2,dbUsername2,dbPassword2,dbDriver2)

        List results = sql.rows(dbQuery2)

        return results

        sql.close()
    }

I managed to use this syntax to act as variable

def productId = new File(RunConfiguration.getProjectDir() + "/Data Files/productId.txt")
dbQuery2 = /SELECT * FROM db.table1 where productId = '$productId.text}'/

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