这可能是一个简单的问题,但我没有在C#中经历过。设置数据表等效
我有2个数据表,1基本上是另一个副本(比如表格来查看信息)。要设置值,这就是我现在所做的:
string attribute1 = "";
string attribute2 = "";
string attribute3 = "";
.....
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_id;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM table1 WHERE [email protected]_parameter", con))
{
cmd.Parameters.AddWithValue("@identifying_parameter", "example");
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
attribute1 = Convert.ToString(reader["attribute1"]);
attribute2 = Convert.ToString(reader["attribute2"]);
attribute3 = Convert.ToString(reader["attribute3"]);
.....
}
con.Close();
}
}
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO table2 (attribute1, attribute2, attribute3, ...) VALUES(@attribute1, @attribute2, @attribute3, ...)", con))
{
cmd.Parameters.AddWithValue("@attribute1", attribute1);
cmd.Parameters.AddWithValue("@attribute2", attribute2);
cmd.Parameters.AddWithValue("@attribute3", attribute3);
....
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
很显然,我可能有很多的属性,那么,有没有更简单的设置表中的每个属性在C#等方式?
如果这两个表在同一个数据库中并且具有相同的模式,那么您可以执行查询:INSERT INTO table2 SELECT * FROM table1 WHERE parameter = @ identify_parameter'。 –
你不能做得比把它转换成一个班轮还好,你应该创建你自己的扩展方法,你需要使用反射 – Coder1409