diff --git a/dialect/base.go b/dialect/base.go index 28332c7..057689b 100644 --- a/dialect/base.go +++ b/dialect/base.go @@ -6,10 +6,16 @@ package dialect import ( "os/exec" + "strings" "github.com/issue9/sliceutil" ) +var ( + quoteApostrophe = strings.NewReplacer("'", "''") // 标准 SQL 用法 + escapeApostrophe = strings.NewReplacer("'", "\\'") // mysql 用法 +) + type base struct { driverName string name string diff --git a/dialect/mysql.go b/dialect/mysql.go index 5f2a158..ca36925 100644 --- a/dialect/mysql.go +++ b/dialect/mysql.go @@ -285,7 +285,7 @@ func (m *mysql) formatSQL(col *core.Column) (f string, err error) { } return "0", nil case string: - return "'" + vv + "'", nil + return "'" + escapeApostrophe.Replace(vv) + "'", nil case time.Time: // datetime return formatTime(col, vv) case sql.NullTime: // datetime diff --git a/dialect/postgres.go b/dialect/postgres.go index e510610..bb8cc2f 100644 --- a/dialect/postgres.go +++ b/dialect/postgres.go @@ -255,7 +255,7 @@ func (p *postgres) formatSQL(col *core.Column) (f string, err error) { switch vv := v.(type) { case string: - return "'" + vv + "'", nil + return "'" + quoteApostrophe.Replace(vv) + "'", nil case time.Time: // timestamp return formatTime(col, vv) case sql.NullTime: // timestamp diff --git a/dialect/sqlite3.go b/dialect/sqlite3.go index e84c958..1d042a1 100644 --- a/dialect/sqlite3.go +++ b/dialect/sqlite3.go @@ -336,7 +336,7 @@ func (s *sqlite3) formatSQL(v any) (f string, err error) { switch vv := v.(type) { case string: - return "'" + vv + "'", nil + return "'" + quoteApostrophe.Replace(vv) + "'", nil case time.Time: // timestamp return "'" + vv.In(time.UTC).Format(datetimeLayouts[0]) + "'", nil case sql.NullTime: // timestamp