dongshenjie3055 2014-12-04 06:54
浏览 194
已采纳

Golang中跨数据库的准备好的语句绑定(如和在何处)

After reading many tutorials, I found that there are many ways to bind arguments on prepared statement in Go, some of them

SELECT * FROM bla WHERE x = ?col1 AND y = ?col2
SELECT * FROM bla WHERE x = ? AND y = ?
SELECT * FROM bla WHERE x = :col1 AND y = :col2
SELECT * FROM bla WHERE x = $1 AND y = $2

First question, what is the cross-database way to bind arguments? (that works on any database)

Second question, none of the tutorial I've read mention about LIKE statement, how to bind arguments for LIKE-statement correctly?

SELECT * FROM bla WHERE x LIKE /*WHAT?*/

Third question, also none of them give an example for IN statement, how to bind arguments for IN statement correctly?

`SELECT * FROM bla WHERE x IN ( /*WHAT?*/ )
  • 写回答

2条回答 默认 最新

  • douzhuo1853 2014-12-04 19:12
    关注

    What is the cross-database way to bind arguments?

    With database/sql, there is none. Each database has its own way to represent parameter placeholders. The Go database/sql package does not provide any normalization facility for the prepared statements. Prepared statement texts are just passed to the underlying driver, and the driver typically just sends them unmodified to the database server (or library for embedded databases).

    How to bind arguments for LIKE-statement correctly?

    You can use parameter placeholders after a like statement and bind it as a string. For instance, you could write a prepared statement as:

    SELECT a from bla WHERE b LIKE ?
    

    Here is an example (error management handling omitted).

    package main
    
    import (
        "database/sql"
        "fmt"
        _ "github.com/go-sql-driver/mysql"
    )
    
    // > select * from bla ;
    // +------+------+
    // | a    | b    |
    // +------+------+
    // | toto | titi |
    // | bobo | bibi |
    // +------+------+
    
    func main() {
    
        // Open connection
        db, err := sql.Open("mysql", "root:XXXXXXX@/test")
        if err != nil {
             panic(err.Error())  // proper error handling instead of panic in your app
        }
        defer db.Close()
    
        // Prepare statement for reading data
        stmtOut, err := db.Prepare("SELECT a FROM bla WHERE b LIKE ?")
        if err != nil {
            panic(err.Error()) // proper error handling instead of panic in your app
        }
        defer stmtOut.Close()
    
        var a string
        b := "bi%"    // LIKE 'bi%'
        err = stmtOut.QueryRow(b).Scan(&a)
        if err != nil {
            panic(err.Error()) // proper error handling instead of panic in your app
        }
        fmt.Printf("a = %s
    ", a)
    } 
    

    Note that the % character is part of the bound string, not of the query text.

    How to bind arguments for IN statement correctly?

    None of the databases I know allows binding a list of parameters directly with a IN clause. This is not a limitation of database/sql or the drivers, but this is simply not supported by most database servers.

    You have several ways to work the problem around:

    • you can build a query with a fixed number of placeholders in the IN clause. Only bind the parameters you are provided with, and complete the other placeholders by the NULL value. If you have more values than the fixed number you have chosen, just execute the query several times. This is not extremely elegant, but it can be effective.

    • you can build multiple queries with various number of placeholders. One query for IN ( ? ), a second query for IN (?, ?), a third for IN (?,?,?), etc ... Keep those prepared queries in a statement cache, and choose the right one at runtime depending on the number of input parameters. Note that it takes memory, and generally the maximum number of prepared statements is limited, so it cannot be used when the number of parameters is high.

    • if the number of input parameters is high, insert them in a temporary table, and replace the query with the IN clause by a join with the temporary table. It is effective if you manage to perform the insertion in the temporary table in one roundtrip. With Go and database/sql, it is not convenient because there is no way to batch queries.

    Each of these solutions has drawbacks. None of them is perfect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退