Click here to Skip to main content
15,881,687 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I AM TRYING TO UPDATE DATA IN A DATABASE...ACCESS DATABASE TO BE PRECISE, AND IT IS THOWING ME AN ERROR ABOVE HOW DI SOLVE IT

What I have tried:

public String UpdateData(String TableName, String ColumName, int WhatToInsert, String UpdatedInfo)
{
    String item;
    OleDbConnection connection = new OleDbConnection();
    connection.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Rental_database .accdb");
    connection.Open();
    item = "UPDATE ["+TableName+"] SET  ["+ColumName+"]="+UpdatedInfo+" WHERE [ID]="+WhatToInsert+"";
    OleDbCommand command = new OleDbCommand(item, connection);
    command.ExecuteNonQuery();
    connection.Close();
    return item;
}
Posted
Updated 11-Jan-23 18:06pm
Comments
Graeme_Grant 11-Jan-23 23:56pm    
Please DO NOT SHOUT, it is rude. Always use normal sentence case!

1 solution

You are not correctly using the OleDbCommand object. Here is a Google Search that will explain how to use it correctly: c# how to use OleDbCommand[^].

Also, as mentioned in your last question, you should never put values into the query string. Doing so opens you to SQL injection attacks[^].

Here is how to update using OleDbCommand:
C#
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = $"UPDATE {TableName} SET {ColumName} = @value WHERE ID = @id";
cmd.Parameters.AddWithValue("@id", WhatToInsert);
cmd.Parameters.AddWithValue("@value", UpdatedInfo);
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
{
    MessageBox.Show("Update Success!");
    cn.Close();`
}
 
Share this answer
 
v2
Comments
BillWoodruff 13-Jan-23 0:42am    
have you actually run this code yourself and verified it works ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900