I have made a program in C# and now I want to update a boolean value in my Access database. This boolean value will always be updated to false. I have absolutely tried everything and there is no change in my value. Please help.
Here is my code :
The [In mail] column is my boolean value. I have tried this query in Access and it works perfectly there.
String query = "UPDATE Ontwikkeldossier SET Ontwikkeldossier.[In mail] = #fals WHERE (((Ontwikkeldossier.[OntwikkeldossierID])=#ontwikkeldossierid));";
using(OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("#fals", OleDbType.Boolean, 1, "[In mail]").Value = false;
cmd.Parameters.Add("#ontwikkeldossierid", OleDbType.Numeric).Value = Convert.ToInt32(newrow.Cells[0].Value.ToString());
cmd.ExecuteNonQuery();
}
Thanks in advance.
updateCmd.Parameters.Add("#3", OleDbType.Boolean).Value = "true";
this worked for me! I have "Yes/No" column in Access. Update command is:
OleDbCommand updateCmd = new OleDbCommand("UPDATE email SET server = #1, port = #2, ssl = #3, utilizator = #4, parola = #5, subiect = #6, email = #7 WHERE ID = #8", connection);
For what it's worth, I just tested the following code and it works for me:
using (var conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\__tmp\testData.accdb;"))
{
conn.Open();
using (var cmd = new OleDbCommand(
"UPDATE Ontwikkeldossier SET [In mail]=? WHERE OntwikkeldossierID=?",
conn))
{
cmd.Parameters.AddWithValue("?", false);
cmd.Parameters.AddWithValue("?", 1);
cmd.ExecuteNonQuery();
}
conn.Close();
}
Should this:
cmd.Parameters.Add("#fals", OleDbType.Boolean, 1, "[In mail]").Value = false;
Instead be:
cmd.Parameters.Add("#fals", OleDbType.Boolean).Value = false; //or zero, since it's an object, the DB might care...
Is the source an issue? If you're supplying the value, why do you want a source for the value?
Of course, since it's always false for you, you could simply change the query and eliminate the parameter altogether:
String query = "UPDATE Ontwikkeldossier SET Ontwikkeldossier.[In mail] = 0 WHERE (((Ontwikkeldossier.[OntwikkeldossierID])=#ontwikkeldossierid));";
Related
I'm trying to update an Access database through my C# web application but I'm currently facing a problem in WHERE statement not updating the records and not returning any errors.
I'm trying update a text field and the condition in my WHERE statement is an integer.
OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = #Title WHERE ID = #ID");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#Title", TextBox1.Text);
cmd.Parameters.AddWithValue("#ID", param2);
I even tried doing it this way
OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = ? WHERE ID = ?");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("?", TextBox1.Text);
cmd.Parameters.AddWithValue("?", param2);
But it's still not updating!
What I found out trying to fix it is that when i replace the first parameter with a string between single quotes (see below), it actually updates the table.
OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = 'test' WHERE ID = #ID");
Does any of you guys have an idea why is this happening?
Edit: This is the full code
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = #Title WHERE ID = #ID");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#Title", TextBox1.Text);
cmd.Parameters.AddWithValue("#ID", param2);
conn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
Edit 2:
This is my code after trying to set the data types, it's still not working.
To clarify, in my Access database ID is "AutoNumber" and Title is "Long Text"
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = ? WHERE ID = ?");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("Title", TextBox1.Text).OleDbType = OleDbType.VarChar;
cmd.Parameters.AddWithValue("ID", param2).OleDbType = OleDbType.Integer;
conn.Open();
try
{
var recordsUpdated = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
When I check the value of recordsUpdated, it returns "1" but the database isn't being updated.
You need to call ExecuteNonquery which executes the statement.
// your OleDbConnection should also be wrapped in a using statement to ensure it is closed
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open(); // open the connection
using(OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = ? WHERE ID = ?")) // wrap in using block because OleDbCommand implements IDisposable
{
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("Title", TextBox1.Text).OleDbType = OleDbType.VarChar; // Title, also set the parameter type
cmd.Parameters.AddWithValue("ID", param2).OleDbType = OleDbType.Integer; // ID, I am guessing its an integer but you should replace it with the correct OleDbType
var recordsUpdated = cmd.ExecuteNonQuery(); // execute the query
// recordsUpdated contains the number of records that were affected
}
}
The order op the Parameters that you add must match the order of the parameters in the sql statement.
Be sure you specify your OleDbType for each parameter so the command does not have to guess what it is. I guessed Title is a varchar and ID is integer, correct this if it is a wrong assumption.
You can replace "?" with parameter names to make the addition of parameters easier to read and keep the ? placeholders in the update statement. Microsoft does this in many of their examples in their documentation
ExecuteNonQuery returns the number of rows affected, capture the result and use it for debugging (see code update)
When I check the value of recordsUpdated, it returns "1" but the database isn't being updated.
If 1 is being returned then 1 record is being updated. Here are 2 trouble shooting tips.
You should make sure that your query is updating the same record you are checking. During debugging capture the value of param2 and manually use that in a select statement in Access to see the Title column of that record SELECT Title FROM Data WHERE ID = [id here]. Also get the value of TextBox1.Text in debugging and check this value against what is returned from the manually executed select query.
As this is Ms Access and the file resides on disk, make sure that you are manually checking against the same database that you are connecting to in your connection string. If you have 2 copies of the database this could easily lead to a wrong conclusion that an update is not being performed.
I have a problem in trying to update a database using SQL update command and DataGridView.
Int16 ID, An;
// update db using sql command, the code does not update the database
SqlCommand cmd = new SqlCommand("update filme set ID = #ID, Nume = #Nume, Gen = #Gen, Descriere = #Descriere, Actori = #Actori, An = #An, Rating = #Rating, Pret = #Pret where ID = #ID");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#ID", SqlDbType.SmallInt).Value = Int16.TryParse("#ID", out ID);
cmd.Parameters.AddWithValue("#Nume", SqlDbType.NVarChar).Value = "#Nume";
cmd.Parameters.AddWithValue("#Gen",SqlDbType.NVarChar).Value = "#Gen";
cmd.Parameters.AddWithValue("#Descriere", SqlDbType.NVarChar).Value = "#Descriere";
cmd.Parameters.AddWithValue("#Actori", SqlDbType.NVarChar).Value = "#Actori";
cmd.Parameters.AddWithValue("#An", SqlDbType.SmallInt).Value = Int16.TryParse("#An", out An) ;
cmd.Parameters.AddWithValue("#Rating", SqlDbType.NVarChar).Value = "#Rating";
cmd.Parameters.AddWithValue("#Pret",SqlDbType.Money).Value = "#Pret";
connection.Open();
cmd.ExecuteNonQuery();
This code does not produce any errors, but does not update the database. Something is wrong but I don't know what.
I use Visual Studio Community and SQL Server 2012. The information from database are displayed in a DataGridView.
Thank you !
You set the #ID parameter with this line
Int16.TryParse("#ID", out ID);
what do you expect to be the result of converting the string #ID to an integer?
And Int16.TryParse returns a boolean, true if the conversion succeed, false otherwise.
Then you use
cmd.Parameters.AddWithValue("#ID", SqlDbType.SmallInt).Value = .....
The second parameter of AddWithValue is the Value to give to the parameter, not the type.
The remainder follows the same pattern and so this code will never work.
As an example, you should write:
SqlCommand cmd = new SqlCommand(#"update filme set Nume = #Nume, Gen = #Gen,
Descriere = #Descriere, Actori = #Actori,
An = #An, Rating = #Rating, Pret = #Pret
where ID = #ID", connection);
cmd.Parameters.Add(new SqlParameter
{ ParameterName = #Nume,
SqlDbType = SqlDbType.Int,
Value = Convert.ToInt32(someTextBox.Text) // Or some datagridview cell...
};
...and so on for the other parameters...
Notice also that I have removed the part about SET ID = #ID because this makes no sense. If you use the ID field as your search condition then updating it with the value that you are searching for could only lead, in the best situation, at no change for the ID field and in the worst situation to changing a different record from the intended one.
The way you use the .AddWithValue is all wrong .....
You have
cmd.Parameters.AddWithValue("#ID", SqlDbType.SmallInt).Value = Int16.TryParse("#ID", out ID);
but you're really defining the parameter name and datatype (which is a good thing!) and then you use the .Value = ... to handle the value assignment.
These lines of code should really be:
cmd.Parameters.Add("#ID", SqlDbType.SmallInt).Value = Int16.TryParse("#ID", out ID);
I bet using this approach, your code will work just fine.
con = new SqlConnection (cs);
SqlCommand UpdateCommand = new SqlCommand("Update Stock Set ConfigID = #ConfigID , Quantity = #Quantity ,TotalPrice =#TotalPrice, StockDate =#StockDate ,Where StockID='" +txtStockID.Text+"'");
UpdateCommand.Parameters.Add("#ConfigID",SqlDbType.Int).Value= txtConfigID.Text;
UpdateCommand.Parameters.Add("#Quantity", SqlDbType.Int).Value = txtQty.Text;
UpdateCommand.Parameters.Add("#TotalPrice", SqlDbType.Int).Value = txtTotalPrice.Text;
UpdateCommand.Parameters.Add("#StockDate", SqlDbType.NVarChar, 50).Value = dtpStockDate.Value;
con.Open();
UpdateCommand.ExecuteNonQuery();
con.Close();
I find this error-message understandable, isn't it? However, you have to assign the connection to the SqlCommand, either by using the constructor or the property Connection:
string updateSQL = #"UPDATE Stock Set ConfigID = #ConfigID,
Quantity = #Quantity,
TotalPrice = #TotalPrice,
StockDate = #StockDate
WHERE StockID = #StockID";
SqlCommand UpdateCommand = new SqlCommand(updateSQL, con);
or
SqlCommand UpdateCommand = new SqlCommand(updateSQL);
UpdateCommand.Connection = con;
Note that i've added a parameter for the StockID in the Where and removed the last comma before the Where.
Note also that you should close connections when you're finished, therefore you can use the using-statement which ensures that it gets disposed/closed even on error:
using(var con = new SqlConnection (cs))
{
// ...
}
how to solve error of “ ExecuteNonQuery: Connection property has not been initialized?”
By initializing the Connection property
UpdateCommand.Connection = con;
UpdateCommand.ExecuteNonQuery();
Also you should wrap your connection object with a using statement to make sure it is properly disposed.
You can also use the connection to create the command:
var command = connection.CreateCommand();
This ensures you have a command initialised with the correct connection. You can set the query string using the property command.CommandText:
command.CommandText = #"SELECT foo FROM foo";
A simple select statement using variable binding gives no rows??
OracleConnection con = new OracleConnection(constr);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "select country_name from hr.countries where country_id = :country_id;
OracleParameter p_country_id = new OracleParameter();
p_country_id.OracleDbType = OracleDbType.Varchar2;
p_country_id.Value = "UK";
cmd.Parameters.Add(p_country_id);
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{} ---> no rows
tried adding parameterName ,direction,size still result is 0???
Any help??
I believe this is all correct but it is written in NotePad. At the very least it should get you on the right track.
using (OracleConnection con = new OracleConnection(constr))
{
con.Open();
using (OracleCommand cmd = con.CreateCommand())
{
cmd.CommandText = "select country_name from hr.countries where country_id = :country_id";
cmd.Parameters.Add("country_id", "UK")
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
// You code here
}
}
}
NOTE: I put the using statements in there because this is always recommended when executing database queries. If an exception occurs the using statement will guarantee your database connection is still closed.
You forgot to give your parameter a name. Do so and it should work:
p_country_id.ParameterName = "country_id";
Thanks for responding guys, My unit test project app.config was pointing to wrong DB schema :(
Grrrrrrrrrrrrr! can't get anything stupid then this :) i will blame on my flu :)
In my code neither of these queries appear to be running. The debug label is printing as "end" so it is executing something inside that code block, just appears it doesn't like the queries?
// Check input is all valid
if (Page.IsValid)
{
debug.Text = "begin";
using (SqlConnection cn = new SqlConnection(
ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand(
"UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO tblSiteSettings (allowProductRatings, allowComments, " +
"siteName, settingDate, isActive) VALUES (#allowRatings, " +
"#allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cn.Close();
}
debug.Text = "end";
}
}
A few questions:
Why are they not executing?
In classic ASP for inserts, updates and deletes I would use con.Execute(query) as supposed to using a recordset, am I running my update statement correctly here?
Is my design of the queries good, or should I be executing them in a different manner?
The reason it's not doing anything is because you're not actually executing the queries. What you need to do is:
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand("UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO tblSiteSettings (allowProductRatings, allowComments, siteName, settingDate, isActive) VALUES (#allowRatings, #allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
It's the line cmd.ExecuteNoneQuery(); that you're missing. There are various different Execute methods exposed by the SqlCommand class, the most commonly used are:
ExecuteNonQuery: Executes a query and returns no result from the query (it does return the rows affected as its return value however)
ExecuteScalar: Executes a query and returns the value in the first column of the first row
ExecuteReader: Executes a query and returns the data to a SqlDataReader
Your are missing
cmd.ExecuteScalar();
You may also reuse you SqlConnection, you can open the connection right after the using (SqlConnection cn = new Sql... statement. You don't have to close the connection when the SqlConnection is in a using block, accordning to the documentation the connection is closed when you are leaving the using block.