[C#]
您可以使用Table-valued parameters 在单个 SQL 查询中发送多行。
流程将是
- 定义
table type。架构将与要插入的参数相同。
- 使用与
table type 完全相同的名称和类型创建一个DataTable。
- 在查询中将
DataTable 作为参数传递。
样本
CREATE TYPE MyTableType AS TABLE
( mytext TEXT,
num INT );
using (SqlConnection connection = new SqlConnection(CloudConfigurationManager.GetSetting("Sql.ConnectionString")))
{
connection.Open();
DataTable table = new DataTable();
// Add columns and rows. The following is a simple example.
table.Columns.Add("mytext", typeof(string));
table.Columns.Add("num", typeof(int));
for (var i = 0; i < 10; i++)
{
table.Rows.Add(DateTime.Now.ToString(), DateTime.Now.Millisecond);
}
SqlCommand cmd = new SqlCommand(
"INSERT INTO MyTable(mytext, num) SELECT mytext, num FROM @TestTvp",
connection);
cmd.Parameters.Add(
new SqlParameter()
{
ParameterName = "@TestTvp",
SqlDbType = SqlDbType.Structured,
TypeName = "MyTableType",
Value = table,
Direction = ParameterDirection.Input,
});
cmd.ExecuteNonQuery();
}
参考:https://docs.microsoft.com/en-us/azure/azure-sql/performance-improve-use-batching#table-valued-parameters
[JAVA]
您可以使用PreparedStatement,创建一批要插入的行(ps.addBatch()),然后一次性插入一批(ps.executeBatch())。
示例:
PreparedStatement ps= con.prepareStatement("INSERT INTO Sample VALUES (?, ?, ?, ?)");
for(int i; i<10; i++){
ps.setString(1, "String1");
ps.setString(2, "String2");
ps.setString(3, "String3");
ps.setInt(4, 1000);
ps.addBatch();
}
ps.executeBatch();
如果要插入的记录很多,您可以创建多个批次并将它们插入到循环本身中。