這可能是一個簡單的問題,但我沒有在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