我有以下 c# 代码:
基本上我从 TableA/Database1 中选择一行并将其插入到 TableA/Database2 中。
然后我再次打开连接并从 TableB/Database1 中选择多行(使用从 TableA/Database1 检索到的 newID)并插入 TableB/Database2。
我的问题是这样做的正确方法吗?还是应该将这些结合起来?如果这些应该结合起来,任何人都可以告诉我实现这一目标的最佳方法吗?
int newID = 0;
using (var con1 = new SqlConnection(conString1))
using (var con2 = new SqlConnection(conString2))
{
con1.Open();
con2.Open();
using (var selectCommand = new SqlCommand(sqlSelect, con1))
{
using (var reader = selectCommand.ExecuteReader())
{
try
{
if (reader != null)
if (reader.Read())
{
using (var insertCommand = new SqlCommand(sqlInsert, conTarget))
{
for (int i = 0; i < reader.FieldCount; i++)
{
insertCommand.Parameters.AddWithValue(
"@" + reader.GetName(i), reader[i]);
}
newID = (int)insertCommand.ExecuteScalar();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
reader.Close();
}
}
}
}
我将 newID 作为选择示例之一的值传递:
Select Id, student as newID, Class from Student where class = 10
using (var con1 = new SqlConnection(ConString1))
{
con1.Open();
var cmd = new SqlCommand(query , con1);
var reader = cmd.ExecuteReader();
using (var con2 = new SqlConnection(conString2))
{
con2.Open();
using (var sbc = new SqlBulkCopy(conString2))
{
sbc.BulkCopyTimeout = 2000;
sbc.DestinationTableName = "student";
try
{
if (reader != null)
sbc.WriteToServer(reader);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
reader.Close();
}
}
}
}