Update query isn't updating records in database? - c#

private void btnUpdate_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Update tb1 set rollno=#rollno WHERE name=#Name", con);
cmd.Parameters.AddWithValue("#Name", txtproject_name.Text);
cmd.Parameters.AddWithValue("#rollno", textroll.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated sucessfully");
}
This is my code for updating data in the database but it is not updating anything... why isn't it working?

Do not use named parameters, use ? instead.
MSDN:
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the
OleDbParameterCollection must directly correspond to the position of
the question mark placeholder for the parameter in the command text.

Which database server you are using? there is difference passing parameters while server changes for example
SQL Server - #Name
MySql - #Name
Oracle - :Name
etc.
if you are using MS Access use as follows
private void btnUpdate_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Update tb1 set rollno=? WHERE name=?", con);
cmd.Parameters.AddWithValue("rollno", textroll.Text);
cmd.Parameters.AddWithValue("name", txtproject_name.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated sucessfully");
}
for more refer
http://www.mikesdotnetting.com/Article/26/Parameter-Queries-in-ASP.NET-with-MS-Access

Related

how to solve the problem(#id needs to be declared) in sqladapter.InsertCommand c# ado.net

I keep getting this error
System.Data.SqlClient.SqlException: La variable scalaire "#id" doit être déclarée.
on the adapter's insert command, even if my value is declared in the parameters
What should I do?
Here is the code
private void BT_Add_Click(object sender, EventArgs e)
{
adapter.SelectCommand.Parameters.AddWithValue("#id", txtID.Text);
adapter.SelectCommand.Parameters.AddWithValue("#name", txtName.Text);
adapter.SelectCommand.Parameters.AddWithValue("#lastname", txtLastName.Text);
adapter.SelectCommand.Parameters.AddWithValue("#adress", txtAdress.Text);
adapter.SelectCommand.Parameters.AddWithValue("#email", txtEmail.Text);
connection.Open();
adapter.InsertCommand = new SqlCommand("insert into client values(#id,#name,#lastname,#adress,#email)", connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Row inserted !! ");
}
You've added parameters to the SelectCommand; this does not automatically add them to the InsertCommand. The two commands are different things
You don't need an adapter here; just make a new SqlCommand, set the SQL, add the parameters to it and execute it

unable to insert data in sql database with c# even no error accur

hy I want to insert new record in my database but am unable to do this even code is fully error free, I added following code in my button click event
here is my code
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
private void btn_Update_Click(object sender, EventArgs e)
{
string query="insert into users(Name,Password)values('ubaid','ali')";
cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
}
I mean insert query is not updating my database, even when I execute my query it return 2 not 0 which means query applied successfully,
not really an answer but the steps you need to take to see whats going on, so we can help you are a bit longer...
you will need to execute the following query, once in your sql management studio, and once in your program ... i suspect the result being different in both cases
select ##SERVERNAME, ##SERVICENAME, db_name(), SCHEMA_NAME()
on the code side please use this:
private void btn_Update_Click(object sender, EventArgs e)
{
// string query="insert into users(Name,Password)values('ubaid','ali')";
// cmd = new SqlCommand(query, con);
// con.Open();
// cmd.ExecuteNonQuery();
// MessageBox.Show("Record Updated Successfully");
// con.Close();
string query="select ##SERVERNAME, ##SERVICENAME, db_name(), SCHEMA_NAME()";
cmd = new SqlCommand(query, con);
con.Open();
using(var rdr = cmd.ExecuteReader())
{
rdr.read();
MessageBox.Show($"{rdr.GetString(0)}, {rdr.GetString(1)}, {rdr.GetString(2)}, {rdr.GetString(3)} ");
}
con.Close();
}
the result should show the name of the server, its instance name, the name of your DB and of the default schema you are using in both cases
example result for my testmachine would look like this:
srv9, MSSQLSERVER, testdb, dbo
expectation in your case:
you will get 2 different results which means that your sql management studio, where you are trying to check if your code did the right thing, is using a different server, instance, database or schema
with the provided information it will be possible to change the used connectionstring so both your clients work on the same database...

Save and retrive rtf text from database using c#

I just finished to save a text from a richtextbox into sql database. Here you have the code:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[FISIER] (File_name,The_text) VALUES (#File_name,#The_text)", con);
cmd.Parameters.Add("#File_name", textBox1.Text);
cmd.Parameters.AddWithValue("#The_text", richTextBox1.Rtf);
cmd.ExecuteNonQuery();
con.Close();
}
Here is the table Click here for table
Now, my problem is that I don't know how to retrive the text from the database. As you see there the text I had saved into The_text and the data type is Text. I want to retrive the data back into richtextbox.
A quick search would have revealed the answer to this. For example, here is some sample code that queries a database table...
// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);
// 2. Call Execute reader to get query results
SqlDataReader rdr = cmd.ExecuteReader();
You can change the table name and fields to match your database.
This code was found at http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson03, but there are millions of other sites that will teach you this stuff.

Not updating values in access database

protected void Button2_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\sandesh.k\Documents\PARAM_REP.accdb;";
OleDbCommand com = new OleDbCommand();
com.CommandText = "UPDATE LOGI SET [PASSWORD]=#PASS,NAME=#NAME,CAPABILITY=#CAPABLE WHERE ID=#ID";
com.Parameters.AddWithValue("#ID", TextBox2.Text);
com.Parameters.AddWithValue("#PASS", TextBox7.Text);
com.Parameters.AddWithValue("#NAME", TextBox5.Text);
com.Parameters.AddWithValue("#CAPABLE", Convert.ToInt32(TextBox6.Text));
con.Open();
com.Connection = con;
com.ExecuteNonQuery();
con.Close();
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('REPORT CREATED SUCCESSFULLY')</script>");
}
You didn't told use what is wrong exactly but..
OleDbCommand does not support named parameters. Actually is supports but it just don't care their names. The only matter is their orders.
Set your parameters with same order that you defined in your command as;
com.Parameters.AddWithValue("#PASS", TextBox7.Text);
com.Parameters.AddWithValue("#NAME", TextBox5.Text);
com.Parameters.AddWithValue("#CAPABLE", Convert.ToInt32(TextBox6.Text));
com.Parameters.AddWithValue("#ID", TextBox2.Text);
Also use using statement to dispose your connections and commands automatically instead of calling Close method manually. And don't use AddWithValue method. It may generate unexpected and surprising results sometimes. Use Add method overloads to specify your parameter type and it's size.
using(var con = new OleDbConnection())
using(var com = con.CreateCommand())
{
// Set your CommandText property.
// Add your parameters with Add method in the same order that you defined.
// Open your connection.
// Execute your query.
}
Also I strongly suspect your ID column should be numeric value instead of character type based on it's name.

C# ASP.NET TSQL Code Behind Upgrade DB

I'm trying to upgrade the db from users' input, but it doesn't work...
I'm using this:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
SqlCommand ncmd = new SqlCommand("Update Utenti Set Nome = #vnome where [Indirizzo E-Mail]=#vem", con);
ncmd.Parameters.AddWithValue("#vem", Session["[Indirizzo E-Mail]"].ToString());
ncmd.Parameters.AddWithValue("#vnome", TextBox2.Text);
ncmd.Connection = con;
con.Open();
ncmd.ExecuteNonQuery();
con.Close();
Label2.Text = "Dati aggiornati con successo!";
Response.Redirect("~/ModificaDati.aspx");
}
When I click on the button it show me the Label2 text, but in the database the "Nome" is not changed, why?
Thanks before for the answers ^^
I would change your method as below
if (Session["[Indirizzo E-Mail]"] != null &&
!string.IsNullOrEmpty(Session["[Indirizzo E-Mail]"].ToString()) &&
!string.IsNullOrEmpty(TextBox2.Text))
{
string vem = Session["[Indirizzo E-Mail]"].ToString();
using (var con = new SqlConnection(strcon))
using (var ncmd = new SqlCommand("Update Utenti Set Nome = #vnome where [Indirizzo E-Mail]=#vem", con))
{
con.Open();
ncmd.Parameters.AddWithValue("#vem", vem);
ncmd.Parameters.AddWithValue("#vnome", TextBox2.Text);
int rows = ncmd.ExecuteNonQuery();
Label2.Text = rows + " Dati aggiornati con successo!";
}
}
Response.Redirect("~/ModificaDati.aspx");
Added input validation, session values can be null, better to check before you update database
when you create SqlCommand you can give the connection, no need to set it again
make sure your SQL is valid
use using statements for disposable objects like SqlConnection, SqlCommand
Your code looks ok. Just make sure you check if SQL is correct as Damith already suggested.
Another thing I’s recommend is additionally validating your parameters for data type correctness before executing the query.
Using this approach you’ll probably avoid a lot of unnecessary exceptions and also be able to provide more user friendly messages. Of course this only applies if user input is non text type
//Data Type verification
DateTime tmp;
if (!DateTime.TryParse(Label2.Text.Trim(), out tmp))
{
//Show error message that this is not a correct data type
}
Open your connection first
con.Open();
ncmd.Connection = con;
Hope it helps

Categories

Resources