普通网友 2018-09-13 05:47
浏览 160
已采纳

Golang和PostgreSQL的创建表给我的问题

Using and following the documentation: https://godoc.org/github.com/lib/pq but can't see after hours and hours and research online to find any good example of passing variables to the db.Exec() I'm building a program that will create new tables depending on certain names entered on the command arguments.

db.Exec(`CREATE TABLE $1(
    ID INT PRIMARY KEY NOT NULL,
    HOST    TEXT    NOT NULL,
    PORTS   TEXT,
    BANNERS TEXT,
    JAVASCRIPT TEXT,
    HEADERS TEXT,
    COMMENTS TEXT,
    ROBOTS  TEXT,
    EMAILS  TEXT,
    CMS     TEXT,
    URLS    TEXT,
    BUSTIN  TEXT,
    VULN    TEXT
    )`,  tablename)

But no luck, I obviously have try to change things around, even I have try to build the CREATE TABLE syntax on a string and have try to pass that instead of db.Exec(string) but no luck neither... can someone give me a hand?

Thanks

  • 写回答

1条回答 默认 最新

  • duanqiao8925 2018-09-14 03:12
    关注

    You can check on https://golang.org/src/database/sql/sql.go?s=39599:39668#L1437, at line 1478, that sql statements will be first prepared then executed.

    In PostgreSQL, prepare are only valid for SELECT, INSERT, UPDATE, DELETE, or VALUES, https://www.postgresql.org/docs/10/static/sql-prepare.html .

    Here you can use Go's fmt.Sprintf to support creating different tables, and check table name manually, SQL table names can contain many special characters, but you can narrow it, mine validation is regexp.MustCompile("^[a-zA-Z_]+[0-9a-zA-Z_]*$") .

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容