是否可以在mysql中进行批量复制

编程入门 行业动态 更新时间:2024-10-28 06:26:56
本文介绍了是否可以在mysql中进行批量复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要在 Mysql 数据库中插入多行.我的行在我的数据集中可用.

I need to insert multiple rows in my Mysql database.my rows are available in my dataset.

我正在使用for循环逐一发送行是正确的方式吗?...

i am using for loop to send the row one by one is that right way?...

推荐答案

您可以使用单个 SQL 语句插入多行,如下所示:

You can insert multiple rows using a single SQL statement like so:

INSERT INTO myTable (col1, col2, col3) VALUES ('myval1', 'myval2', 'myval3'), ('myotherval1', 'myotherval2', 'myotherval3'), ('anotherval1', 'anotherval2', 'anotherval3');

更新:

MarkR 在他的评论中是正确的 - 如果您正在从用户那里收集数据,或者您正在编译信息,您可以使用以下内容动态构建查询:

MarkR is right in his comment - if you're collecting data from a user, or you're compiling information, you can build the query dynamically with something like:

StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("INSERT INTO myTable (col1, col2, col3) VALUES "); for(int i=0;i<myDataCollection.Count;i++) { stringBuilder.Append("(" + myDataCollection[i].Col1 + ", " + myDataCollection[i].Col2 + ", " + myDataCollection[i].Col3 + ")"); if (i<myDataCollection.Count-1) { stringBuilder.Append(", "); } else { stringBuilder.Append(";"); } } string insertStatement = stringBuilder.ToString();

需要注意的两点:

  • 如果您接受来自用户的输入,那么清理所有用户输入非常重要,否则恶意用户可能会修改/删除/删除您的整个数据库.有关详细信息,请在 Google 上搜索SQL 注入".
  • 我使用的是 StringBuilder 类,而不是使用字符串原语并简单地追加(即字符串 s = "Insert..."; s+="blah blah blah"),因为它的 StringBuilder 追加速度更快,因为它不被视为一个数组,因此在附加到它时不需要调整自身的大小.
  • If you are accepting input from a user, it is very important to sanitize all user inputs, otherwise malicious users could modify/delete/drop your entire database. For more info, google "SQL Injections."
  • I'm using the StringBuilder class, rather than using a string primitive and simply appending (ie. string s = "Insert..."; s+="blah blah blah") because it's StringBuilder is faster at appending, because it is not treated as an array, and so does not need to resize itself as you append to it.
  • 更多推荐

    是否可以在mysql中进行批量复制

    本文发布于:2023-10-23 22:21:54,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1522166.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:批量   mysql

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!