Reputation: 143
I intend to populate an access DB table that has three columns; Entity(text type), Date and Value(double type). I wrote the following code by going through some online links. Although the code runs fine, the table has no data. I am probably missing some part. Any advice?
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
EDIT: Still not working
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
Upvotes: 2
Views: 174
Reputation: 4808
You need create the connection to the database and execute the query.
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
is whatever your connection string is to your database.
In this example you don't need to explicitly close the connection after the query is executed as the connection is wrapped in a using
block, and so will be disposed of once it has exited the block.
Upvotes: 4