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
Related
I have two SQL queries:
SqlCommand cmdone = new SqlCommand("update HardwareDetails Set Transstat = #Transstat where AssetNo = #AssetNo", con);
cmdone.Parameters.AddWithValue(#"Transstat", "Raised");
cmdone.Parameters.AddWithValue(#"AssetNo", txtAsset.Text);
cmdone.ExecuteNonQuery();
cmdone.Dispose();
And:
SqlCommand cmd = new SqlCommand("Insert into TransferRequest(FrmName,FrmEmpId,ToName) values (#FrmName,#FrmEmpId,#ToName", con);
cmd.Parameters.AddWithValue(#"FrmName", txtfrm.Text);
cmd.Parameters.AddWithValue(#"FrmEmpId", Global.transferorid);
cmd.Parameters.AddWithValue(#"ToName", txtName.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
Is there a way to combine them into a single query?
Put a semi-colon between the two SQL statements, and add all the parameters.
using (SqlCommand cmd = new SqlCommand("UPDATE HardwareDetails SET Transstat = #Transstat WHERE AssetNo = AssetNo; INSERT INTO TransferRequest (FrmName, FrmEmpId, ToName) VALUES (#FrmName, #FrmEmpId, #ToName)", con))
{
cmd.Parameters.AddWithValue(#"Transstat", "Raised");
cmd.Parameters.AddWithValue(#"AssetNo", txtAsset.Text);
cmd.Parameters.AddWithValue(#"FrmName", txtfrm.Text);
cmd.Parameters.AddWithValue(#"FrmEmpId", Global.transferorid);
cmd.Parameters.AddWithValue(#"ToName", txtName.Text);
cmd.ExecuteNonQuery();
}
Comments:
Its best practice (because its safer) to create your cmd within a using block.
AddWithValue should not be used, instead create the SqlParameter using its constructor and specify the type and precision. E.g. cmd.Parameters.Add(new SqlParameter("#Transstat", SqlDataType.VarChar, 6) { Value = "Raised"});
As pointed out by Liam as it stands this does break the Single Responsibility Principle. Personally I would only use this method if the two statements are linked/related in some way.
string query = #"
update HardwareDetails Set Transstat = #Transstat where AssetNo = #AssetNo
Insert into TransferRequest(FrmName,FrmEmpId,ToName) values (#FrmName,#FrmEmpId,#ToName)";
SqlCommand cmd= new SqlCommand(query,con);
cmd.Parameters.AddWithValue(#"Transstat", "Raised");
cmd.Parameters.AddWithValue(#"AssetNo", txtAsset.Text);
cmd.Parameters.AddWithValue(#"FrmName", txtfrm.Text);
cmd.Parameters.AddWithValue(#"FrmEmpId", Global.transferorid);
cmd.Parameters.AddWithValue(#"ToName", txtName.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
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;
}
I'm using the following code to clear a database table:
public void ClearAll()
{
SqlCommand info = new SqlCommand();
info.Connection = con;
info.CommandType = CommandType.Text;
info.CommandText = "edit_.Clear()";
}
Why does it not work?
With a sql command you usually pass a TSQL statement to execute. Try something more like,
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["con"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "DELETE FROM Edit_ ";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
You need to execute the command, so info.Execute() or info.ExecuteNonQuery().
Try info.CommandText='DELETE FROM edit_';
The CommandText attribute is the TSQL statement(s) that are run.
You also need a info.ExecuteNonQuery();
1) Decide whether to use a TRUNCATE or a DELETE statement
Use TRUNCATE to reset the table with all its records and indexes:
using (SqlCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "TRUNCATE TABLE [dbo].[Edit_]";
command.ExecuteNonQuery();
}
Use DELETE to delete all records but do not reset identity/auto increment columns
using (SqlCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "DELETE FROM [dbo].[Edit_]";
command.ExecuteNonQuery();
}
Note that there is another line in the samples. In the sample you provided the SQL statement never gets executed until you call one of the ExecuteXXX() methods like ExecuteNonQuery().
2) Make sure you use the correct object (are you sure its called edit_?). I recommend to put the schema before the table name as in the examples before.
3) Make sure you use the correct connection string. Maybe everything worked fine on the production environment ;-)
Why does this return null?
//seedDate is set to DateTime.Now; con is initialized and open. Not a problem with that
using (SqlCommand command = new SqlCommand("fn_last_business_date", con))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#seed_date", seedDate);//#seed_date is the param name
object res = command.ExecuteScalar(); //res is always null
}
But when I call this directly in the DB as follows:
select dbo.fn_last_business_date('8/3/2011 3:01:21 PM')
returns '2011-08-03 15:01:21.000'
which is the result I expect to see when I call it from code
Why, why, why?
Why does everyone insist on the select syntax?..
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("calendar.CropTime", c))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RETURN_VALUE", SqlDbType.DateTime).Direction = ParameterDirection.ReturnValue;
cmd.Parameters.AddWithValue("#d", DateTime.Now);
cmd.ExecuteNonQuery();
textBox1.Text = cmd.Parameters["#RETURN_VALUE"].Value.ToString();
}
try:
using (SqlCommand command = new SqlCommand("select dbo.fn_last_business_date(#seed_date)", con))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#seed_date", seedDate);//#seed_date is the param name
object res = command.ExecuteScalar(); //res is always null
}
You are actually getting an error that isn't being caught. You don't call scalar udfs like you call stored procedures.
Either wrap the udf in a stored proc, or change syntax. I'm not actually sure what that is because it isn't common...
Ah ha: see these questions:
How to use SQL user defined functions in .NET?
Calling user defined functions in Entity Framework 4
I am getting exception: "Specific cast is not valid", here is the code
con.Open();
string insertQuery = #"Insert into Tender (Name, Name1, Name2) values ('Val1','Val2','Val3');Select Scope_Identity();";
SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.ExecuteNonQuery();
tenderId = (int)cmd.ExecuteScalar();
In the interests of completeness, there are three issues with your code sample.
1) You are executing your query twice by calling ExecuteNonQuery and ExecuteScalar. As a result, you will be inserting two records into your table each time this function runs. Your SQL, while being two distinct statements, will run together and therefore you only need the call to ExecuteScalar.
2) Scope_Identity() returns a decimal. You can either use Convert.ToInt32 on the result of your query, or you can cast the return value to decimal and then to int.
3) Be sure to wrap your connection and command objects in using statements so they are properly disposed.
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
int tenderId = (int)(decimal)command.ExecuteScalar();
}
}
Try this:-
con.Open();
string insertQuery = #"Insert into Tender (Name, Name1, Name2) values ('Val1','Val2','Val3');Select Scope_Identity();";
SqlCommand cmd = new SqlCommand(insertQuery, con);
tenderId = Convert.ToInt32(cmd.ExecuteScalar());
EDIT
It should be this as it is correctly pointed out that scope_identity() returns a numeric(38,0) :-
tenderId = Convert.ToInt32(cmd.ExecuteScalar());
Note: You still need to remove the:-
cmd.ExecuteNonQuery();
Test the following first:
object id = cmd.ExcuteScalar()
Set a break point and have a look at the type of id. It is probably a Decimal and cannot directly be casted to int.
it needs Convert.ToInt32(cmd.ExecuteScalar());