简体   繁体   中英

Updating MS Access Database in C# Application

thanks in advance for any help or suggestions.

I have found many posts on here which are relating to my issue however I am struggling to find out what exactly I need to change to solve my problem of updating an MS Access database from a C# application. So I apologize if people feel this post is too similar to others.

Here is my update code:

OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\DATA2\Nescot Students\Y13\s0234438\dboCanada.accdb";
conn.Open();

string query = "UPDATE Products SET [Product_Name] = @ProName, [Product_Description] = @ProDes, [Standard_Cost] = @StaCos, [Category] = @Cat, [List_Price] = @LisPri  WHERE ID = '" + Convert.ToInt16(lblID.Text) + "'";
OleDbCommand cmd = new OleDbCommand(query, conn) /*{ CommandType = CommandType.Text }*/;
cmd.Parameters.AddWithValue("@ProName", txtProducts.Text);
cmd.Parameters.AddWithValue("@ProDes", txtDescription.Text);
cmd.Parameters.AddWithValue("@StaCos", Convert.ToDecimal(txtPrice.Text));
cmd.Parameters.AddWithValue("@Cat", txtCat.Text);
cmd.Parameters.AddWithValue("@LisPri", Convert.ToDecimal(txtListPrice.Text));

int rowsAffected = cmd.ExecuteNonQuery();
conn.Close();

I'm sure that I am very close to getting this to work but I don't know where to go from here... The error that is coming up is

'Data type mismatch in criteria expression.'

WHERE ID = '" + Convert.ToInt16(lblID.Text) + "'"

This is wrong. If your ID column is numeric you don't need to use single quotes.

Why don't you add it also as a parameter since you did for the others? Like;

..WHERE ID = @id;
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(lblID.Text));

Also use using statement to dispose your OleDbConnection and OleDbCommand .

string ConnString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\DATA2\Nescot Students\Y13\s0234438\dboCanada.accdb";
using(OleDbConnection conn = new OleDbConnection(ConnString ))
using(OleDbCommand cmd = conn.CreateCommand())
{
   cmd.CommandText = @"UPDATE Products SET [Product_Name] = @ProName, [Product_Description] = @ProDes, [Standard_Cost] = @StaCos, [Category] = @Cat, [List_Price] = @LisPri  WHERE ID = @id";
   cmd.Parameters.AddWithValue("@ProName", txtProducts.Text);
   cmd.Parameters.AddWithValue("@ProDes", txtDescription.Text);
   cmd.Parameters.AddWithValue("@StaCos", Convert.ToDecimal(txtPrice.Text));
   cmd.Parameters.AddWithValue("@Cat", txtCat.Text);
   cmd.Parameters.AddWithValue("@LisPri", Convert.ToDecimal(txtListPrice.Text));
   cmd.Parameters.AddWithValue("@id", Convert.ToInt32(lblID.Text));

   conn.Open();
   int rowsAffected = cmd.ExecuteNonQuery();
   conn.Close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM