I am trying to pass some information to an Access Database, however I'm not sure if I am using ExecuteNonQuery()
correctly. Here is the code I'm using:
public void WriteToDB(string connStr, string tblName)
{
string[] accounts = { "@ID", "@Date", "@Line Item", "@Ranking Item", "@Item Attribute", "@Current_Period_Ranking(b)" };
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
OleDbCommand CmdSQL = new OleDbCommand(string.Format("Insert into [{0}] ([ID], [Date], [Line Item], [Ranking Item], [Ranking]) VALUES(?,?,?,?,?)",tblName),conn);
CmdSQL.Parameters.AddWithValue("@ID", 1);
CmdSQL.Parameters.AddWithValue("@Date", "6/20/2016");
CmdSQL.Parameters.AddWithValue("@Line Item", this.ItemName);
CmdSQL.Parameters.AddWithValue("@Ranking Item", "Ranking");
CmdSQL.Parameters.AddWithValue("@Ranking", this.Rank.GetLineItem(3));
CmdSQL.ExecuteNonQuery();
CmdSQL.Parameters.AddWithValue("@ID", 2);
CmdSQL.Parameters.AddWithValue("@Date", "6/20/2016");
CmdSQL.Parameters.AddWithValue("@Line Item", this.ItemName);
CmdSQL.Parameters.AddWithValue("@Ranking Item", "Price");
CmdSQL.Parameters.AddWithValue("@Ranking", this.Price);
CmdSQL.ExecuteNonQuery();
CmdSQL.Parameters.AddWithValue("@ID", 3);
CmdSQL.Parameters.AddWithValue("@Date", "6/20/2016");
CmdSQL.Parameters.AddWithValue("@Line Item", this.ItemName);
CmdSQL.Parameters.AddWithValue("@Ranking Item", "Pounds");
CmdSQL.Parameters.AddWithValue("@Ranking", this.Pounds);
CmdSQL.ExecuteNonQuery();
CmdSQL.Parameters.AddWithValue("@ID", 4);
CmdSQL.Parameters.AddWithValue("@Date", "6/20/2016");
CmdSQL.Parameters.AddWithValue("@Line Item", this.ItemName);
CmdSQL.Parameters.AddWithValue("@Ranking Item", "Opportunity");
CmdSQL.Parameters.AddWithValue("@Ranking", this.Opportunity);
CmdSQL.ExecuteNonQuery();
}
When I run this bit of code, the Access DB only shows the 1's.
Since you are using the same command, you have to clear out the parameters afterwards:
CmdSQL.ExecuteNonQuery();
CmdSQL.Parameters.Clear();
CmdSQL.Parameters.AddWithValue("@ID", 4);
....
On a side note, dates should be dates in a database, not strings. Your database looks questionable if you have a bunch of tables with this same structure. Why not just one table and a field that distinguishes what type of row it is. It would make your queries easier. It's also very common and beneficial to put those disposable database objects in using blocks.