Is that possible to do bulk copy in mysql(是否可以在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中进行批量复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在mysql中进行批量复制


基础教程推荐
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01