将数据插入数据库C#中的表

时间:2016-01-06 16:04:03

标签: 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

1 个答案:

答案 0 :(得分:4)

您需要创建与数据库的连接并执行查询。

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块中,因此一旦退出块就会被处置掉。

https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.executenonquery(v=vs.110).aspx