Tin*_*Tin 5 mysql database dataset
我需要在我的Mysql数据库中插入多行.我的数据集中有可用的行.
我正在使用for循环逐行发送行是正确的方法吗?...
您可以使用单个 SQL 语句插入多行,如下所示:
INSERT INTO myTable (col1, col2, col3) VALUES ('myval1', 'myval2', 'myval3'), ('myotherval1', 'myotherval2', 'myotherval3'), ('anotherval1', 'anotherval2', 'anotherval3');
Run Code Online (Sandbox Code Playgroud)
更新:
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();
Run Code Online (Sandbox Code Playgroud)
需要注意的两个要点: