[英]Insert data into a table in database C#
我打算填充一個具有三列的訪問數據庫表。 實體(文本類型),日期和值(雙精度類型)。 我通過一些在線鏈接編寫了以下代碼。 盡管代碼運行良好,但該表沒有數據。 我可能缺少了一部分。 有什么建議嗎?
for (int i = 0; i < model.CDFResults.Count; i++)
{ // connection details to the DB here...
for (int j = 0; j < model.CDFResults[i].DataPoints.Count; j++)
{
OleDbCommand myAccessCommand = new OleDbCommand();
myAccessCommand.CommandType = CommandType.Text;
myAccessCommand.CommandText = "INSERT INTO TypeCurves([Entity],[Date],[Value])VALUES(?,?,?)";
myAccessCommand.Parameters.AddWithValue("@Entity", model.CDFResults[i].catname_db);
myAccessCommand.Parameters.AddWithValue("@Date", model.CDFResults[i].DataPoints[j].dt);
myAccessCommand.Parameters.AddWithValue("@Value", model.CDFResults[i].DataPoints[j].CDFVal);
} // end of FOR(j) loop
} // end of FOR(i) loop
編輯:仍然無法正常工作
for (int i = 0; i < model.CDFResults.Count; i++)
{ // connection details to the DB here...
for (int j = 0; j < model.CDFResults[i].DataPoints.Count; j++)
{
OleDbConnection thisConnection = new OleDbConnection(connectionname);
thisConnection.Open();
OleDbCommand myAccessCommand = new OleDbCommand();
myAccessCommand.CommandType = CommandType.Text;
myAccessCommand.CommandText = "INSERT INTO TypeCurves([Entity],[Date],[Value])VALUES(?,?,?)";
myAccessCommand.Parameters.AddWithValue("@Entity", model.CDFResults[i].catname_db);
myAccessCommand.Parameters.AddWithValue("@Date", model.CDFResults[i].DataPoints[j].dt);
myAccessCommand.Parameters.AddWithValue("@Value", model.CDFResults[i].DataPoints[j].CDFVal);
myAccessCommand.ExecuteNonQuery();
} // end of FOR(j) loop
} // end of FOR(i) loop
您需要創建與數據庫的連接並執行查詢。
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string query = "INSERT INTO TypeCurves([Entity],[Date],[Value])VALUES(@Entity,@Date,@Value)";
OleDbCommand myAccessCommand = new OleDbCommand(query, connection);
myAccessCommand.Parameters.AddWithValue("@Entity", model.CDFResults[i].catname_db);
myAccessCommand.Parameters.AddWithValue("@Date", model.CDFResults[i].DataPoints[j].dt);
myAccessCommand.Parameters.AddWithValue("@Value", model.CDFResults[i].DataPoints[j].CDFVal);
connection.Open();
myAccessCommand.ExecuteNonQuery();
}
connectionString
是您與數據庫的連接字符串。
在此示例中,您無需在執行查詢后顯式關閉連接,因為連接被包裝在using
塊中,因此一旦退出該塊將被丟棄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.