douxiao0400
2016-10-17 01:28 阅读 154

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

    点赞 评论 复制链接分享
  • dtjw6660 dtjw6660 2016-10-17 01:33

    You can't use parameters for table or column names in SQL. You will have to escape the variable part manually and build the table name in code and inject it in the SQL string before sending it to the database.

    As well, the PostgreSQL engine is built in such a way that it does not allow variables at any place in a CREATE statement. This means that the engine does will not accept any parameters when running such a query.

    点赞 评论 复制链接分享

相关推荐