douli2876 2017-12-14 08:53
浏览 824
已采纳

在Golang中动态创建PostgreSQL表

I am using "database/sql" package in GO. I want to create a table of variable name.

Only way I can think of is-

db.Exec(`CREATE TABLE`+table_name+`;`)

But it is not safe as there can be SQL injection.

  • 写回答

3条回答 默认 最新

  • dsnhalq37505 2017-12-14 09:01
    关注

    I don't code in GO, but this would probably be safe for injection:

    tx.Prepare(`do $$ begin execute format($f$create table %I()$f$,$1); end; $$;`)
    

    and then

    stmt.Exec(table_name)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongli8979 2017-12-14 09:43
    关注

    Just use placeholders like:

    db.Exec("CREATE TABLE $1", "table_name")

    wikipedia:

    With most development platforms, parameterized statements that work with parameters can be used (sometimes called placeholders or bind variables) instead of embedding user input in the statement. A placeholder can only store a value of the given type and not an arbitrary SQL fragment. Hence the SQL injection would simply be treated as a strange (and probably invalid) parameter value.

    评论
  • douzhangkui2467 2017-12-14 15:13
    关注

    Its just like @Vao Tsun said:

    stmt, err := db.Prepare("CREATE TABLE $1")
    if err != nil {
        log.Fatal(err)
    }
    defer stmt.Close()
    
    result, err := stmt.Exec("DB_NAME_HERE")
    

    Go through the original documentation and look at their example as well for clear understanding.

    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 unity 绘画方面的问题
  • ¥15 FTP 明明给了权限但是还是550 Permission denied问题
  • ¥20 Java的kafka错误unknowHostException
  • ¥20 gbase 8a没有lisense,需要获取一个lisense
  • ¥15 前端的3d饼图不知道用啥框架做的
  • ¥15 算法问题 斐波那契数 解答
  • ¥15 VS2019 SPY++ 获取句柄操作
  • ¥15 Facebook 获取广告
  • ¥15 PID算法的输出结果如何转换成pwm
  • ¥15 java文本解密算法