douxiao0400 2016-10-17 01:28
浏览 431
已采纳

Golang为“ CREATE TABLE”准备了语句

I'm finding that create table statements are not recognizing wildcard characters I want to insert. How would I do something like with a prepared statement in golang?

                    stmt, err := tx.Prepare(`
                    CREATE TABLE table_number_$1 (
                            guid character varying(64) NOT NULL,
                            number integer,
                            name character varying(64),
                            PRIMARY KEY (guid),
                            CONSTRAINT some_onstraint
                            CHECK ((number = $2))
                    )`)
                    if err != nil {
                            return err 
                    }   
                    defer stmt.Close()
                    if _, err := stmt.Exec(
                            string(table_number),
                            table_number; err != nil {
                            tx.Rollback()
                            return err 
                    }  

The error I get when I print it out is: sql: expected 0 arguments, got 2

EDIT: obviously I know I could build the string like normal, but was wondering if there's a built in way.

  • 写回答

2条回答 默认 最新

  • dsasd12314 2016-10-17 02:25
    关注

    It's not possible in PostgreSQL because:

    1. PostgreSQL's bind parameters may only be used for literals, not identifiers. That's because the parser has to know what the identifiers are in order to parse the query correctly, but bind parameters are only sent after parsing. So you can't use parameters for table names etc.

    2. PostgreSQL doesn't support bind parameters in utility statements (anything other than insert/update/delete/select) anyway.

    Some drivers support client-side parameter substitution and escaping for identifiers via a different placement parameter syntax, but as far as I can tell Go's does not. So you'll have to use string interpolation, carefully. Remember to always enclose the identifier in "double quotes" and double any embedded quotes, so a table name my "table"! becomes "my ""table!" in SQL.

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

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法