我需要在我的 Mysql 数据库中插入多行。我的行在我的数据集中可用。
我正在使用 for 循环逐行发送是正确的方法吗?...
最佳答案
您可以像这样使用单个 SQL 语句插入多行:
INSERT INTO myTable (col1, col2, col3) VALUES ('myval1', 'myval2', 'myval3'), ('myotherval1', 'myotherval2', 'myotherval3'), ('anotherval1', 'anotherval2', 'anotherval3');
更新:
MarkR 在他的评论中是正确的 - 如果您正在从用户那里收集数据,或者您正在编译信息,您可以使用类似的东西动态构建查询:
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();
需要注意的两点:
- 如果您正在接受来自用户的输入,那么对所有用户输入进行清理非常重要,否则恶意用户可能会修改/删除/删除您的整个数据库。有关更多信息,请在谷歌上搜索“SQL 注入(inject)”。
- 我正在使用 StringBuilder 类,而不是使用字符串基元并简单地附加(即 string s = "Insert..."; s+="blah blah blah"),因为它的 StringBuilder 附加速度更快,因为它不被视为数组,因此不需要在附加到它时调整自身大小。
关于database - 是否可以在 mysql 中进行批量复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2821725/