I can't seem to figure out why my update statement isn't working. I have a lot of similar operations to the database, inserting, selecting, deleting and they are all working well. Except for update, it doesn't seem to work. I've tried the SQL statement in MS Access on the same database, replacing the '#parameters' with values and it worked just fine.
I tried debugging and all the data from my object is valid and correct. But when I execute the command, it returns 0 and no rows were updated. My code is bellow, keep in mind that I'm rather new to C#.
public int UpdateActiviteit(Activiteit activiteit)
{
connection.Open();
OleDbCommand command = new OleDbCommand("Update Activiteit set Naam = #naam, Beschrijving = #beschrijving, TypeActiviteitID = #typeActiviteitId, BonusPunten = #bonusPunten, Datum = #datum where id = #id", connection);
command.Parameters.Add(new OleDbParameter("#naam", activiteit.Naam));
command.Parameters.Add(new OleDbParameter("#beschrijving", activiteit.Beschrijving));
command.Parameters.Add(new OleDbParameter("#typeActiviteitId", activiteit.TypeActiviteitId));
command.Parameters.Add(new OleDbParameter("#bonusPunten", activiteit.BonusPunten));
command.Parameters.Add(new OleDbParameter("#datum", activiteit.Datum));
command.Parameters.Add(new OleDbParameter("#id", activiteit.ID));
int rowsAffected = command.ExecuteNonQuery();
connection.Close();
return rowsAffected;
}
Related
I am trying to update my ms access db with windows application and I am having a hard time. When I run it I don't get any errors but it does update like once or twice when I test it but then doesn't work again if I do it again a third time.
This is the code I use
Conn.Open();
Command.CommandType = CommandType.Text;
Command.CommandText ="UPDATE TABLE SET c_qty=#qty WHERE id = #ID";
Command.Parameters.AddWithValue("#qty", txtQty.Text);
Command.Parameters.AddWithValue("#ID", txtID.Text);
Command.ExecuteNonQuery();
Conn.Close();
I felt I was doing this right or on the right track of having it correct but seems to be more of a issue then I thought. Any help would be great
Quantity and Id are hopefully integers and you should pass them as such.
Also Table is a reserved word, if this really is the name of your table you should enclose it with square brackets.
You should also pass in the correct db types in your parameters and not use AddWithvalue which does not allow this.
Code
Conn.Open();
Command.CommandType = CommandType.Text;
Command.CommandText ="UPDATE [TABLE] SET c_qty= ? WHERE id = ?";
Command.Parameters.Add(new OleDbParameter("#qty", OleDbType.Int) {Value = int.Parse(txtQty.Text)});
Command.Parameters.Add(new OleDbParameter("#ID", OleDbType.Int) {Value = int.Parse(txtID.Text)});
var rowsUpdated = Command.ExecuteNonQuery();
// output rowsUpdated to the log, should be 1 if id is the PK
Conn.Close();
Finally use using blocks for your Disposables. If you were to get an Exception here then connection would remain open until Garbage collection runs which means you might have a problem with other connection attempts to this Access database.
Revised with using blocks
using (OleDbConnection Conn = new OleDbConnection("connectionStringHere"))
using (OleDbCommand Command = new OleDbCommand("UPDATE [TABLE] SET c_qty= ? WHERE id = ?", Conn))
{
Command.Parameters.Add(new OleDbParameter("#qty", OleDbType.Int) {Value = int.Parse(txtQty.Text)});
Command.Parameters.Add(new OleDbParameter("#ID", OleDbType.Int) {Value = int.Parse(txtID.Text)});
Conn.Open();
var rowsUpdated = Command.ExecuteNonQuery();
// output rowsUpdated to the log, should be 1 if id is the PK
}
Finally OleDbCommand does not support named parameters, see OleDbCommand.Parameters
I'm using Microsoft Access file as database. I have no problem with SELECT and INSERT queries but when I try to UPDATE, record in database does not change.
Below is the code I use to run update. There are no exceptions or errors in debug log.
cnn = new OleDbConnection(connetionString);
OleDbCommand command = new OleDbCommand("UPDATE [Wpisy] SET [wpis]=#wpis, [id_kat]=#id_kat, [tytul]=#tytul WHERE [ID]=#id_wpis" , cnn);
command.Parameters.Add(new OleDbParameter("#wpis", tresc_wpisu.Text));
command.Parameters.Add(new OleDbParameter("#id_kat", lista_kategorii.SelectedValue));
command.Parameters.Add(new OleDbParameter("#tytul", tytul_wpisu.Text));
command.Parameters.Add(new OleDbParameter("#id_wpis", Request["id"].ToString() ));
command.Connection = cnn;
try
{
if(cnn.State.ToString() != "Open")
cnn.Open();
command.ExecuteNonQuery();
cnn.Close();
}
catch (OleDbException ex)
{
Response.Clear();
Response.Write(ex);
Response.End();
}
I would go to Microsoft Access and enter the command there and see what happens. It should tell you how many rows was affected. If it says zero rows, then break your query into smaller pieces, such as:
select * where [ID]=value
And then you should be able to track down where the problem is.
I know this isn't an exact answer, but there are some quirks with working with MS Access.
Here is an example method for you with some proper exception handling for databases. For Object, create a class that represents a row fields in your table. I use Exception ex instead of the db library exception since I use DataReaders for selects.
private String connectionString = "someOleDbConnectionString";
public String UpdateObject(Object obj)
{
OleDbConnection connection = GetMyOleDbConnection(); //returns new OleDbConnection with proper connection string
String updateSql = "UPDATE [Wpisy] SET [wpis]=#wpis, [id_kat]=#id_kat, [tytul]=#tytul WHERE [ID]=#id_wpis";
OleDbCommand command = new OleDbCommand(updateSql, connection);
command.CommandType = System.Data.CommandType.Text; //this can be changed if you have stored procedures in your db.
//you may have to define the OleDbType of the parameter being defined
command.Parameters.Add(new OleDbParameter("#wpis", OleDbType.VarChar, obj.tresc_wpisu));
command.Parameters.Add(new OleDbParameter("#id_kat", OleDbType.VarChar, obj.lista_kategorii));
command.Parameters.Add(new OleDbParameter("#tytul", OleDbType.VarChar, obj.tytul_wpisu));
command.Parameters.Add(new OleDbParameter("#id_wpis", OleDbType.Integer, obj.id.ToString()));
return Execute(connection, command);
}
private OleDbConnection GetMyOleDbConnection()
{
return new OleDbConnection(connectionString);
}
private String Execute(OleDbConnection connection, OleDbCommand command)
{
try
{
connection.Open();
command.ExecuteNonQuery();
//I also know with Access databases,
//sometimes you have to close the table if it is open in MS Access
connection.Close();
return "SUCCESS";
}
catch (Exception ex)
{
connection.Close(); //important or you will have left open connections
Response.Clear();
Response.Write(ex.Message);
Response.End();
return ex.Message;
}
}
I could be wrong, but from what I remember, OleDB doesn't allow named parameters, but instead use "?" as a place-holder, and the parameters need to be added in the same sequence as they appear in the SQL statement. such as
String updateSql = "UPDATE [Wpisy] SET [wpis]=?, [id_kat]=?, [tytul]=? WHERE [ID]=?";
command.Parameters.Add(new OleDbParameter("parm_wpis", OleDbType.VarChar, obj.tresc_wpisu));
command.Parameters.Add(new OleDbParameter("parm_id_kat", OleDbType.VarChar, obj.lista_kategorii));
command.Parameters.Add(new OleDbParameter("parm_tytul", OleDbType.VarChar, obj.tytul_wpisu));
command.Parameters.Add(new OleDbParameter("parm_id_wpis", OleDbType.Integer, obj.id.ToString()));
Naming the parameters is just for clarification to know which is which. One other issue might be that you named the parameters by the same name as the column being updated, and that may have been the issue almost like a constant...
set X = X instead of now set X = parmX... there is no ambiguity the you are setting to the PARAMETER value being applied. But overall, I do think it will work via using "?" as the parameter place-holder.
I have a simple insert statement to a table in an SQLite database on MonoDroid.
When inserting to the database, it says
SQLite error Insufficient parameters supplied to the command at Mono.Data.Sqlite.SqliteStatement.BindParameter
I think there is either a bug, or the error message is misleading. Because I only have 5 parameters and I am providing 5 parameters, so I cannot see how this be right.
My code is below, and any help would be greatly appreciated.
try
{
using (var connection = new SqliteConnection(ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandTimeout = 0;
command.CommandText = "INSERT INTO [User] (UserPK ,Name ,Password ,Category ,ContactFK) VALUES ( #UserPK , #Name , #Password , #Category , #ContactFK)";
command.Parameters.Add(new SqliteParameter("#Name", "Has"));
command.Parameters.Add(new SqliteParameter("#Password", "Has"));
command.Parameters.Add(new SqliteParameter("#Cateogry", ""));
command.Parameters.Add(new SqliteParameter("#ContactFK", DBNull.Value));
command.Parameters.Add(new SqliteParameter("#UserPK", DbType.Guid) {Value = Guid.NewGuid()});
var result = command.ExecuteNonQuery();
return = result > 0 ;
}
}
}
catch (Exception exception)
{
LogError(exception);
}
Your spelling for #Category in INSERT statement is different from added parameter.
You have:
command.Parameters.Add(new SqliteParameter("#Cateogry", ""));
^^^^^^^^^^^
//#Category
Where it should be:
Modify your statement to:
command.Parameters.Add(new SqliteParameter("#Category", ""));
This has already been answered correctly, but I wish to add, for further information:
This specific SQLite error string can also be generated if any of the #Parameters are spelled differently in the INSERT statement vs the AddWithValue or .Add(new SqliteParameter... statements.
I am developing a web application and I am calling stored procedure that has insert statement using below code
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "StoredProc1";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlParameter parm = new SqlParameter("#ReturnValue", SqlDbType.Int);
parm.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(parm);
command.Parameters.Add(new SqlParameter("#A", SqlDbType.BigInt)).Value = gui.A;
command.Parameters.Add(new SqlParameter("#B", SqlDbType.Int)).Value = gui.B;
command.Parameters.Add(new SqlParameter("#C", SqlDbType.Decimal)).Value = gui.C;
command.Parameters.Add(new SqlParameter("#D", SqlDbType.Float)).Value = gui.D;
command.Parameters.Add(new SqlParameter("#E", SqlDbType.Float)).Value = gui.E;
command.Parameters.Add(new SqlParameter("#F", SqlDbType.NVarChar)).Value = gui.F;
command.ExecuteNonQuery();
conn.Close();
returnValue = Convert.ToInt32(parm.Value);
But I am getting an error
Arithmetic overflow error converting int to data type numeric
on the ExecuteNonQuery() line. May I know what I am missing?
Thanks
Anjanaa
The actual problem is not entirely in .NET:
Check the store procedure to see if the is any calculated value(s) that may exceed the size of a particular type (i.e. A column of data type int may be calculated to equate the size of data type bigint). The potion that is going to contain that information should be of the same data type (i.e. if this information is contained in a temporary table the temporary table should contain a column of that size to contain the data, if a variable is used the variable should be of size that may contain the data, etc)
The property / field / variable that is going to contain that data should be of a similar data type (i.e. smallint - sql = short - .NET, etc).
I have a simple insert statement to a table in an SQLite database on MonoDroid.
When inserting to the database, it says
SQLite error Insufficient parameters supplied to the command at Mono.Data.Sqlite.SqliteStatement.BindParameter
I think there is either a bug, or the error message is misleading. Because I only have 5 parameters and I am providing 5 parameters, so I cannot see how this be right.
My code is below, and any help would be greatly appreciated.
try
{
using (var connection = new SqliteConnection(ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandTimeout = 0;
command.CommandText = "INSERT INTO [User] (UserPK ,Name ,Password ,Category ,ContactFK) VALUES ( #UserPK , #Name , #Password , #Category , #ContactFK)";
command.Parameters.Add(new SqliteParameter("#Name", "Has"));
command.Parameters.Add(new SqliteParameter("#Password", "Has"));
command.Parameters.Add(new SqliteParameter("#Cateogry", ""));
command.Parameters.Add(new SqliteParameter("#ContactFK", DBNull.Value));
command.Parameters.Add(new SqliteParameter("#UserPK", DbType.Guid) {Value = Guid.NewGuid()});
var result = command.ExecuteNonQuery();
return = result > 0 ;
}
}
}
catch (Exception exception)
{
LogError(exception);
}
Your spelling for #Category in INSERT statement is different from added parameter.
You have:
command.Parameters.Add(new SqliteParameter("#Cateogry", ""));
^^^^^^^^^^^
//#Category
Where it should be:
Modify your statement to:
command.Parameters.Add(new SqliteParameter("#Category", ""));
This has already been answered correctly, but I wish to add, for further information:
This specific SQLite error string can also be generated if any of the #Parameters are spelled differently in the INSERT statement vs the AddWithValue or .Add(new SqliteParameter... statements.