Update to the database didn't work - c#

I got the problem. I want to update the data to the database, but the database won't update.
Here is the code:
Updated Below Code:
else if (firstForm.textBox1.Text == "Seranne")
{
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Maximum = Convert.ToDecimal(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
newVal = textBoxQuantityContainer[index].Value - Convert.ToDecimal(dReader["Quantity"].ToString());
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN ('");
}
index += 1;
}
conn.Close();
dReader.Close();
}
}
private void UpdateQuantity()
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Updated Successfully", "Success");
}
private void button1_Click(object sender, EventArgs e)
{
UpdateQuantity();
}
Above code all worked, excepts for updating the Quantity to the database. What I mean is, I set the Quantity in database to 100, when I set Quantity to 10 in my program and update it, the database should be update the Quantity to 90 (because 100 - 10), but it is still at 100.
Could I wrong somewhere?
Here is the link of the screenshots:
(ScreenShot 1)
https://www.dropbox.com/s/rph5iuh371rc9ny/Untitled.png
(ScreenShot 2)
https://www.dropbox.com/s/5q8pyztqy7ejupy/Capture.PNG
In the Screenshot 1, I already set the quantity to 10 and the messagebox show that the data has been updated successfully and the data in the database supposed to be 90 (because 100-10). But, in the Screenshot 2 where the database is, the Quantity still at 100.
Thanks in advance!

You have an OleDbCommand but you are not executing the query against the database.
You need to open the OleDbConnection which you have not included in your code (if it even exists). It should look something like:
connection.Open();
Where connection is an OleDbConnection object.
Also your query does not look complete.
UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN ("
Is not valid SQL.
The UPDATE statement should look something like:
UPDATE [Table] SET Quantity = newVal WHERE Code IN (Val1, Val2, Val3)
You will also want to change that to use SQL paramerterized queries to prevent SQL Injection.

Related

insert,update in single button clickin winforms

I am not getting, how to do insert and update of the data in C# WinForms on single button click.
private void save_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=Sai;database=kaur; user id=sa;password=azxc;";
cn.Open();
string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
string clas = null;
clas = comboBox1.Text;
string section = null;
section = comboBox2.Text;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into studetail values('" + textBox1.Text + "','" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "')";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
if (n > 0)
MessageBox.Show(n + " Row Inserted.");
else
MessageBox.Show("Insertion failed.");
SqlDataAdapter da = new SqlDataAdapter("select * from studetail ", cn);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
You can add a deletion before the insertion:
private void save_Click(object sender, EventArgs e)
{
DeletePerson(id); // add this
SqlConnection cn = new SqlConnection();
...
}
public void DeletePerson(int id)
{
using(SqlConnection connection = new SqlConnection(credentials))
{
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "delete from studetail where someUniqeIdColumn = " + id;
cmd.ExecuteNonQuery();
}
}
Using responsible to dispose the connection.
Consider using Entity Framework or LINQ to SQL.
You are exposed to SQL injection.
First off the SQL query isn't quite right. It should look something like the following:
INSERT INTO studetail (columnName1, columnName2, ...columnNameN)
VALUES (value1, value2, ...valueN);
Where the column names are the columns where you want data to be inserted, and the values are the data you want inserted into said columns.
You should also be disposing the connection by wrapping the connection within a using statement.
using(var con = new SqlConnection(connectionString))
{
con.Open();
//rest of code that needs a connection here
}
Additionally, you need to be wary of SQL injection. I highly suggest reading this example from the MSDN website. It will give you an example of using an SQL Update and avoiding SQL injection with use of SqlCommand.Paramaters property.
You should also have a Primary Key in your database tables, if you don't already, so you can uniquely identify each record in a table.
To do an update and a save on the same button, you will need to check if a row already exists for the data that is being edited. This when a Primary comes in handy. You will want to check your database to see if a record already exists
SELECT 1 FROM studetail WHERE <Condition>
The WHERE condition will be the way you uniquely identify (a Primary Key) a row in your table. If the rows in the table are uniquely identified, the above SQL statement will return 1 if a value exists, which means you can UPDATE or 0 if no record exists, so you can INSERT

Updating records in SQL Server database using ASP.NET

I am new to ASP.NET, I am facing some difficulty in updating records inside database in ASP.NET. My code is showing no errors, but still the records are not being updated. I am using SQL Server 2012.
Code behind is as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null)
{
con.Open();
string query = "Select * from Customers where UserName ='" + Session["user"] + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
txt_name.Text = reader["CustName"].ToString();
txt_phonenumber.Text = reader["Contact"].ToString();
txt_address.Text = reader["CustAddress"].ToString();
txt_cardnum.Text = reader["CustAccountNo"].ToString();
txt_city.Text = reader["CustCity"].ToString();
txt_emailaddress.Text = reader["Email"].ToString();
txt_postalcode.Text = reader["CustPOBox"].ToString();
Cnic.Text = reader["CustCNIC"].ToString();
}
con.Close();
}
else
{
Response.Redirect("Login.aspx");
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd2 = con.CreateCommand();
SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "Select CustID from Customers where UserName = '" + Session["user"] + "'";
int id = Convert.ToInt32(cmd1.ExecuteScalar());
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "update Customers set CustName='" + txt_name.Text + "',CustCNIC='" + Cnic.Text + "',Email='" + txt_emailaddress.Text + "',CustAccountNo='" + txt_cardnum.Text + "',CustAddress='" + txt_address.Text + "',CustPOBox='" + txt_postalcode.Text + "' where CustID='" + id + "'";
cmd2.ExecuteNonQuery();
con.Close();
}
Help will be much appreciated. THANKS!
After debugging the result i am getting is this
cmd2.CommandText "update Customers set CustName='Umer Farooq',CustCNIC='42101555555555',Email='adada#gmail.com',CustAccountNo='0',CustAddress='',CustPOBox='0' where CustID='6'" string
Here Account Number And POBOX is 0 and address is going as empty string. But i have filled the text fields
First thing to do to fix this is to use good ADO techniques, using SqlParameters for the passed in values; and not the risky SQL Injection method of concatenating strings together.
This first portion does just that. I have added in the int sqlRA variable to read the results of the non-query, which will return Rows Affected by the query. This is wrapped in a simple try...catch routine to set the value to negative 1 on any error. Other error handling is up to you. That makes your code look something like this:
cmd1.Parameters.AddWithValue("#SessionUser", Session["User"]);
int id = Convert.ToInt32(cmd1.ExecuteScalar());
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "UPDATE Customers SET CustName = #CustName, CustCNIC = #CustCNIC, Email = #Email, CustAccountNo = #CustAccountNo, CustAddress = #CustAddress, CustPOBox = #CustPOBox WHERE (CustID = #CustID)";
cmd2.Parameters.AddWithValue("#CustName", txt_name.Text);
cmd2.Parameters.AddWithValue("#CustCNIC", Cnic.Text);
cmd2.Parameters.AddWithValue("#Email", txt_emailaddress.Text);
cmd2.Parameters.AddWithValue("#CustAccountNo", txt_cardnum.Text);
cmd2.Parameters.AddWithValue("#CustAddress", txt_address.Text);
cmd2.Parameters.AddWithValue("#CustPOBox", txt_postalcode.Text);
cmd2.Parameters.AddWithValue("#CustID", id);
int sqlRA
try { sqlRA = cmd2.ExecuteNonQuery(); }
catch (Exception ex) {
sqlRA = -1;
// your error handling
}
/* sqlRA values explained
-1 : Error occurred
0 : Record not found
1 : 1 Record updated
>1 :Multiple records updated
*/
Now reading through your code, all we are doing with the first query is mapping the Session["User"] to id, and then using that id in the second query to do the update, and that Username is not updated in the second. Waste of a query most likely, as we could use the Session["User"] to do the update. That will bring you down to this query, and still bring back that Rows Affected value back:
cmd0.CommandType = CommandType.Text;
cmd0.CommandText = "UPDATE Customers SET CustName = #CustName, CustCNIC = #CustCNIC, Email = #Email, CustAccountNo = #CustAccountNo, CustAddress = #CustAddress, CustPOBox = #CustPOBox WHERE (UserName = #SessionUser)";
cmd0.Parameters.AddWithValue("#CustName", txt_name.Text);
cmd0.Parameters.AddWithValue("#CustCNIC", Cnic.Text);
cmd0.Parameters.AddWithValue("#Email", txt_emailaddress.Text);
cmd0.Parameters.AddWithValue("#CustAccountNo", txt_cardnum.Text);
cmd0.Parameters.AddWithValue("#CustAddress", txt_address.Text);
cmd0.Parameters.AddWithValue("#CustPOBox", txt_postalcode.Text);
cmd0.Parameters.AddWithValue("#SessionUser", Session["User"]);
int sqlRA
try { sqlRA = cmd0.ExecuteNonQuery(); }
catch (Exception ex) {
sqlRA = -1;
// your error handling
}
/* sqlRA values explained
-1 : Error occurred
0 : Record not found
1 : 1 Record updated
>1 :Multiple records updated
*/
When BtnSubmit fires the event, the code in the Page_Load runs before the codes in BtnSubmit, replacing the values placed in the TextBox with the values from the Database before the Update takes place.

Incorrect syntax near '(' when updating record in database

My code is producing an Incorrect syntax near '(' exception. I have tried two different ways but they both produce the same exception. I am trying to update a record in the database.
Here is my code and the line that produces the exception is the Execute non query line. The updater.Fill(dtable) which is commented out also produces the same exception.
protected void btnSave_Click(object sender, EventArgs e)
{
int found = 0; // No match found so far
// Get the current selected Manufacturer
string currentManufacturer = grdManufact.SelectedRow.Cells[1].Text;
string currentIsModerated = grdManufact.SelectedRow.Cells[3].Text;
// Connect to the database
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
SqlConnection conn = new SqlConnection(strConnectionString);
conn.Open();
// Try to find if new record would be a duplicate of an existing database record
if (txtManufactureName.Text != currentManufacturer)
{
string findrecord = "SELECT * From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "'";
SqlDataAdapter adpt = new SqlDataAdapter(findrecord, conn);
DataTable dt = new DataTable();
found = adpt.Fill(dt);
}
if (found == 0) // New record is not a duplicate you can proceed with record update
{
String query;
if (checkBoxModerated.Checked)
{
query = "UPDATE VehicleManufacturer (ManufacturerName, ManufacturerDescription, Ismoderated) Values ('" + txtManufactureName.Text + "','" + txtDescription.Text + "','true') WHERE ManufacturerName = " + currentManufacturer + ";";
}
else
{
query = "UPDATE VehicleManufacturer (ManufacturerName, ManufacturerDescription, Ismoderated) Values ('" + txtManufactureName.Text + "','" + txtDescription.Text + "','false') WHERE ManufacturerName = " + currentManufacturer + ";";
}
using (SqlCommand command = new SqlCommand(query, conn))
{
command.ExecuteNonQuery();
}
//using (SqlDataAdapter updater = new SqlDataAdapter(command))
// {
// DataTable dtable = new DataTable();
// updater.Fill(dtable);
// }
txtMessage.Text = "Manufacturer record changed Successfully";
txtManufactureName.Text = "";
txtDescription.Text = "";
checkBoxModerated.Checked = false;
}
else
{ // Record is a duplicate of existing database records. Give error message.
txtMessage.Text = "Sorry, that manufacturer name already exists.";
}
}
You are using the incorrect syntax for UPDATE statements.
Instead of
UPDATE Table (Fields) VALUES (Values) WHERE ...
It should be
UPDATE Table SET Field1=Value1, Field2=Value2 WHERE ...
Additionally, you have a SQL injection vulnerability (although this is not the reason for your exception).
Do not use string concatenation for SQL queries with user input. Use prepared statements instead.
Try this approach , it's safer also:
var isModerated = checkBoxModerated.Checked ; //true or false
//var isModerated = (checkBoxModerated.Checked)? 'true' : 'false' ;
command.Text = "UPDATE VehicleManufacturer
SET ManufacturerName = #manufacturerName,
ManufacturerDescription = #manufacturerDescription,
IsModerated = #isModerated
WHERE ManufacturerName = #manufacturer_name";
command.Parameters.AddWithValue("#manufacturerName", txtManufactureName.Text);
command.Parameters.AddWithValue("#manufacturerDescription", txtDescription.Text);
command.Parameters.AddWithValue("#isModerated", isModerated);
command.Parameters.AddWithValue("#manufacturer_name", txtManufactureName.Text);
command.ExecuteNonQuery();

How to Access Specific Fields of Data from Database

I am working on a inventory software in which I want to access the ProductName and Product Price by Comparing it With the ProductCode, the Data I've Already Stored in Database table named ProductLog, the Data in Product Log is:
ItemNO Productode ProductName ProductPrice
1 123 lux 58
2 321 soap 68
now I want that I only enter productCode in my textbook named txtProductCode, and press tab then ProductPrice(txtProductPrice) and ProductName(txtProductName) boxes fills automatically.
The code I tried to compare the Productcode and access values is:
private void txtProdcutCode_Leave(object sender, EventArgs e)
{
///////////////////////////////////////////////////////////////////////
InitializeComponent();
string sql;
int productCode = 0;
productCode = Convert.ToInt32(txtProdcutCode.Text);
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, dbo.ProductLog.ProductName";
sql = " WHERE ProductLog.ProductCode = " + txtProdcutCode.Text + "";
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
while (sdr.Read())
{
txtProductPrice.Text = sdr["ProductPrice"].ToString();
txtProductName.Text = sdr["ProductName"].ToString();
}
//lblTotalQuestion.Text = intQNo.ToString();
sdr.Close();
rs = null;
cn.Close();
/////////////////////////////////////////////////////////////////////////
}
but in line productCode = Convert.ToInt32(txtProdcutCode.Text); it says Input string was not in a correct format.
Please help me out with this problem.
EDIT:
I've also tried this code :
private void txtProdcutCode_Leave(object sender, EventArgs e)
{
///////////////////////////////////////////////////////////////////////
string sql;
// int productCode = 0;
//productCode = Convert.ToInt32(txtProdcutCode.Text);
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, AND dbo.ProductLog.ProductName";
sql = " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
while (sdr.Read())
{
txtProductPrice.Text = sdr["ProductPrice"].ToString();
txtProductName.Text = sdr["ProductName"].ToString();
}
//lblTotalQuestion.Text = intQNo.ToString();
sdr.Close();
rs = null;
cn.Close();
/////////////////////////////////////////////////////////////////////////
}
but it says Incorrect syntax near the keyword 'WHERE'. means I am making mistake in calling database table in my query, but I am not able to find out the mistake ...
There are some issues with your SQL.
You were originally overwriting the sql variable and only ended up with a WHERE clause;
You don't have a FROM statement so the database doesn't know where you're trying to retrieve records from.
The use of AND in a SELECT statement is incorrect; you just need commas to separate the fields.
You're never selecting ProductPrice from the DB, but selecting ProductName twice!
You're not using parameterized SQL for your query, leaving your app open to SQL injection attacks.
To address this (points 1-4, I will leave point 5 for your own research),
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, AND dbo.ProductLog.ProductName";
sql = " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
Should be
sql += "SELECT ProductName, ProductPrice";
sql += " FROM dbo.ProductLog";
sql += " WHERE ProductCode = '" + txtProdcutCode.Text + "'";
Note: This answer assumes that the value of txtProductCode.Text is an integer!
EDIT: It turns out that the column, ProductCode, was a VarChar. For OP
and others reading this question, when you get SQL conversion errors
check your column datatype in SQL server and make sure it matches what
you're submitting.
That's the basics. There are many other improvements that can be made but this will get you going. Brush up on basic SQL syntax, and once you get that down, look into making this query use a parameter instead of directly placing txtProductCode.Text into your query. Good luck!
Never call InitializeComponent method twice.It's creating your form and controls and it's calling in your form's constructor.Probably when you leave your textBox it's creating again and textBox will be blank.therefore you getting that error.Delete InitializeComponent from your code and try again.
Update: your command text is wrong.here you should use +=
sql += " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
But this is not elegant and safe.Instead use paramatirezed queries like this:
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT dbo.ProductLog.ProductName,dbo.ProductLog.ProductName WHERE dbo.ProductLog.ProductCode = #pCode";
cmd.Parameters.AddWithValue("#pCode", txtProdcutCode.Text );

SQL code is timing out

My SQL code inserts 10,000 records into a table from list. If record already exists, it updates a few fields.
Currently it taking more than 10 minutes and timing out unless I restrict the number of records to process. Is there anything in my code which I can do to solve this problem.
foreach(RMSResponse rmsObj in rmsList) {
try {
string connectionString = #"server=localhost\sqlexpress;" + "Trusted_Connection=yes;" + "database=MyDB; " + "connection timeout=30";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
string str = "";
str += "SELECT * ";
str += "FROM RMSResponse ";
str += "WHERE LeadID = #RecruitID";
int LeadID;
Boolean IsPositive = true;
SqlCommand selectCommand = new SqlCommand(str, conn);
selectCommand.CommandType = CommandType.Text;
selectCommand.Parameters.Add(new SqlParameter("#RecruitID", rmsObj.RecruitID));
SqlDataReader sqlDataReader = selectCommand.ExecuteReader();
bool hasRows = sqlDataReader.HasRows;
while (sqlDataReader.Read()) {
LeadID = sqlDataReader.GetInt32(1);
IsPositive = sqlDataReader.GetBoolean(2);
IsPositive = (IsPositive == true) ? false : true;
Console.WriteLine("Lead ID: " + LeadID + " IsPositive: " + IsPositive);
}
sqlDataReader.Close();
if (hasRows) {
SqlCommand updateCommand = new SqlCommand("UPDATE RMSResponse set IsPositive=#IsPositive, OptOutDate=#OptOutDate where LeadID=#LeadID", conn);
updateCommand.Parameters.AddWithValue("#LeadID", rmsObj.RecruitID);
updateCommand.Parameters.AddWithValue("#IsPositive", IsPositive);
updateCommand.Parameters.AddWithValue("#OptOutDate", DateTime.Now);
updateCommand.ExecuteNonQuery();
sqlDataReader.Close();
}
if (!hasRows) {
SqlCommand insertCommand = new SqlCommand("INSERT INTO RMSResponse (LeadID, IsPositive, ReceivedDate) " + "VALUES(#LeadID, #IsPositive, #ReceivedDate)", conn);
insertCommand.Parameters.AddWithValue("#LeadID", rmsObj.RecruitID);
insertCommand.Parameters.AddWithValue("#IsPositive", true);
insertCommand.Parameters.AddWithValue("#ReceivedDate", DateTime.Now);
int rows = insertCommand.ExecuteNonQuery();
}
} catch (SqlException ex) {
Console.WriteLine(ex.Message);
}
}
You can move the update to SQL - all you are doing is setting the OptOutDate to be today. You can pass in the list of lead IDs to a batch update statement.
To insert records, you could bulk insert into a staging table, then execute SQL to insert the data for IDs that aren't already in the table.
There isn't much logic in your C#, so pulling the data out then putting it back in is making it unnecessarily slow.
If you don't want to go down this root, then other tips include:
Open one connection outside of the loop
Create one SqlCommand object outside of the loop and reuse it by resetting the paramenters
Change your select SQL to only select the columns you need, not *
A simple update or insert statement should never take 10 mins.
SqlServer is a very good database.
Create an index on LeadID on your table RMSResponse.
If your foreach is looping over many records, definitely consider a stored procedure, stored procedures will reduces a lot of the time taken.
If you want to Update or Insert(UPSERT) look at the Merge command added in SqlServer 2008.

Categories