如何在golang的sql查询中使用通配符

How to use wildcard in sql query in golang

query := "select p.project_id,p.name,p.org_id,p.user_id,p.email,p.status_ind,p.approver,p.favorite,p.create_timestamp,t.name as tagname,count(b.name) as total,t.colorCode from project p inner join tag t on p.project_id = t.project_id  ";
    q2 := " left join build b on p.project_id = b.project_id AND b.status_ind = \"created\" AND p.status_ind = :status group by p.project_id, t.colorCode "
    //query := "select project.project_id,project.name,project.org_id,project.user_id,project.email,project.status_ind,project.approver,project.favorite,project.create_timestamp,tag.name AS tagname, tag.colorCode from project INNER JOIN tag on project.project_id = tag.project_id where status_ind=:status "
    if q["name"] != "" {
        query = query  + " AND p.name LIKE %:name " 
    }
    query+=q2
    query += " ORDER BY create_timestamp DESC "
    query += " LIMIT :limit;"

这里的name是参数,是一个golang变量,来自json请求。每当我点击 API.

时,它都会向我抛出无效 sql 的错误

关于 SQL 语法要记住两点:

  • LIKE 的参数必须是字符串。

  • 参数占位符不得位于 SQL 字符串定界符内。

因此您需要将 LIKE 的参数设为 '%' 和参数值的串联字符串。

有两种方法可以做到这一点。

第一种方法是使用 CONCAT() 连接文字字符串 '%' 和您的参数:

query := `
  SELECT ...
  FROM project p 
  INNER JOIN tag t ON p.project_id = t.project_id  
  LEFT JOIN build b ON p.project_id = b.project_id 
    AND b.status_ind = 'created' 
    AND p.status_ind = ? 
    AND p.name LIKE CONCAT('%', ?)
  GROUP BY p.project_id, t.colorCode
  ORDER BY create_timestamp DESC
  LIMIT ?`

rows, err := db.Query(query, status, name, limit)

第二种方法是只使用参数占位符,并在将字符串传递给查询之前在 Go 代码中连接字符串。

query := `
  SELECT ...
  FROM project p 
  INNER JOIN tag t ON p.project_id = t.project_id  
  LEFT JOIN build b ON p.project_id = b.project_id 
    AND b.status_ind = 'created' 
    AND p.status_ind = ? 
    AND p.name LIKE ?
  GROUP BY p.project_id, t.colorCode
  ORDER BY create_timestamp DESC
  LIMIT ?`

namePattern := "%" + name

rows, err := db.Query(query, status, namePattern, limit)

我在上面的示例中展示了使用 Go 反引号字符串来更轻松地制作可能包含文字引号字符的多行字符串。这是我在 Go 中编写 SQL 查询的方式。

据我所知,MySQL只支持位置查询参数占位符,不支持命名查询参数占位符。