在 Golang 中动态创建 PostgreSQL 表

Shu*_*ary 4 sql postgresql go

我在 GO 中使用“database/sql”包。我想创建一个具有动态名称的表。

我能想到的唯一办法是——

db.Exec(`CREATE TABLE`+table_name+`;`)
Run Code Online (Sandbox Code Playgroud)

但这并不安全,因为可能存在 SQL 注入。
有没有更好的方法来实现这一目标?

Vao*_*sun 5

我不在 GO 中编码,但这对于注入可能是安全的:

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

进而

stmt.Exec(table_name)
Run Code Online (Sandbox Code Playgroud)