doz97171 2019-01-10 04:31
浏览 16

mysql的语法数组

what syntax for add data Array into database, i found for postgresql is : pg.Array

 // "ins" is the SQL insert statement
ins := "INSERT INTO posts (title, tags) VALUES ($1, $2)"

// "tags" is the list of tags, as a string slice
tags := []string{"go", "goroutines", "queues"}

// the pq.Array function is the secret sauce
_, err = db.Exec(ins, "Job Queues in Go", pq.Array(tags))
  • 写回答

1条回答 默认 最新

  • duanhanglekr37902 2019-01-10 05:43
    关注

    A couple of points here that I'll break up, which mostly comes from lack of clarity in your question:

    First

    pq.Array is used to convert array values into safe lists in PostgreSQL, such as the following statement:

    db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401}))
    

    Where the resulting query is:

    SELECT * FROM t WHERE id = ANY(235, 401)
    

    This is intended to help you safely craft query values irrelevant of types, from lists, which is not how you're using it with your question.

    Second

    If you're simply trying to marshal the value into a comma-separated list in your database column, ie:

    | title   | tags                 |
    |---------|----------------------|
    | my post | go,goroutines,queues |
    

    You don't need a special function within the SQL driver. You simply need to create the value, and let the prepared statement do its thing:

    tags := []string{"go, goroutines, queues"}
    q := "INSERT INTO posts (title, tags) VALUES ($1, $2)"
    _, _ = db.Exec(q, "mypost", strings.Join(tags, ","))
    

    Third

    You'd probably be even BETTER served, using relationships within MySQL to accomplish what you're doing:

    posts
    | id | title   |
    |----|---------|
    | 1  | my post |
    
    tags
    | id | tag        |
    |----|------------|
    | 1  | go         |
    | 2  | goroutines |
    | 3  | queues     |
    
    posts_tags
    | posts_id | tags_id |
    |----------|---------|
    | 1        | 1       |
    | 1        | 2       |
    | 1        | 3       |
    

    This will help you save space by not saving duplicate data, and remove the need to understand the serialization method within the database (plus, this is what relational databases do). Then, when you select the table, you can craft JOIN statements to retrieve the data as needed. I highly recommend reading up on many to many relationships within MySQL.

    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错