C# Sql Server update with multiple where clauses and multiple id fields - c#

I am getting Unclosed quotation mark after the character string ''. and I have tried everything any help would be greatly appreciated.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sipConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string query = "select dealercode, dropdate, couponno from coupon where dealercode = '" + DEALERCODETextBox.Text + "' and dropdate = '" + DROPDATETextBox.Text + "' and COUPONNO = '" + COUPONCOUNTTextBox.Text +"','";
SqlCommand cm = new SqlCommand(query, conn);
cm.Parameters.AddWithValue("#couponcount", COUPONCOUNTTextBox.Text);
cm.Parameters.AddWithValue("#totalrev", GRANDTOTALTextBox.Text);
cm.ExecuteNonQuery();
conn.Close();

In the last of your query string
and COUPONNO = '" + COUPONCOUNTTextBox.Text +"','";
replace +"','"; with "'";
Note: Your query string also lack of Parameters

You use paramters to add the values, but you don't use the parameters in the query:
string query = "select dealercode, dropdate, couponno from coupon where dealercode = #dealercode and dropdate =#dropdate and COUPONNO = #couponcount;";
SqlCommand cm = new SqlCommand(query, conn);
cm.Parameters.AddWithValue("#couponcount", COUPONCOUNTTextBox.Text);
cm.Parameters.AddWithValue("#dealercode ", DEALERCODETextBox.Text);
cm.Parameters.AddWithValue("#dropdate ", DROPDATETextBox.Text);

Replace with this line:
string query = "select dealercode, dropdate, couponno
from coupon where dealercode = '" + DEALERCODETextBox.Text + "'
and dropdate = '" + DROPDATETextBox.Text + "'
and COUPONNO = '" + COUPONCOUNTTextBox.Text +"'";
SqlCommand cm = new SqlCommand(query, conn);

Related

SqlCommand doesn't UPDATE and DELETE database when used in ASP.NET

I am having trouble with UPDATE and DELETE data in database when working with ASP.NET web form, the code work well with Windows form so I don't know what I did wrong. The code is suppose to update the Gridview with new edited data but when I click edit button, nothing happen to the gridview as well as the datatable.
This is just an exercise that there is no security requirement so I just want to know how to make it work first.
protected void Edit_btn_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
command.CommandText = ("UPDATE WareHouse SET [Name] = '" + Name_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Number] = '" + Number_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Storage] = '" + Storage_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Shelf] = '" + Shelf_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Brand] = '" + Brand_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM WareHouse", sqlCon);
DataTable ds = new DataTable();
ad.Fill(ds); // Fill t with data from Adapter a
GridView1.DataSource = ds; // Get data from Source t
GridView1.DataBind();
}
and for delete data
protected void Remove_btn_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
command.CommandText = "DELETE FROM WareHouse WHERE [Name] = '" + Name_Field.Text + "' AND [Number] = '" + selectedNumber + "' AND [Storage] = '" + selectedStorage + "' AND [Shelf] = '" + selectedShelf + "' AND [Brand] = '" + selectedBrand + "'";
command.ExecuteNonQuery();
clear();
showData();
}
Aside these 2 function, there are other two that do adding and searching from database which also use SqlCommand and they work fine without problem. Is there any problem with my query?
Storage, Shelf and Brand wouldn't be updated since you are updating [Number] to have the value of Number_Field.Text and then comparing with selectedName in where clause.
It will help you a great deal to put all this SQL code in SP with parameters and call it from ASP.Net code.
Ok.I also faced this issue back when I was learning ASP.NET.
But i had a little different env.
I had a datagrid to play with and any updates in datagrid content should reflect back in DB table upon clicking update button.
So I had below query to populate the grid.
Try
Dim UpperCase As String = UCase(HostnameTextBox.Text)
Dim sql As String = "select * from HOST_DETAILS where upper(HOSTNAME) like '%" + UpperCase + "%'"
da = New OracleDataAdapter(sql, conn)
ds.Clear()
da.Fill(ds, "TEST")
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
And the below one to update the table on the Update button click.
conn.Open()
Try
Dim ocb As New OracleCommandBuilder
ocb = New OracleCommandBuilder(da)
da.Update(ds, "TEST")
MessageBox.Show("Information Updated")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
conn.Close()
Also make sure DataAdapter da is global and is defined right after public class so it can be accessed from both.
Dim da As New OracleDataAdapter
Hope this helps.

Why is my SQL code in C# not working?

I wrote a SQL command to save some items in my database. But when I run it, it gives an error message:
And here is my code:
public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
{
if (beoordelingBest < beoordeling)
{
titelBest = titel;
beoordelingBest = beoordeling;
}
string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
command = new SqlCommand(queryString, con);
Can someone please help me with this? I can't figure it out.
Use parametererized queries and do not use string concatination. This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example).
If you have multiple queries each unique parameter value should have its own parameter name/value
Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable
Never reuse connections as global objects, create, use, and destroy them when needed.
Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary.
var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT #a1Voornaam, #a1Achternaam, FilmID from Films WHERE titel = #title";
using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
command.Parameters.Add(new SqlParameter("#a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
command.Parameters.Add(new SqlParameter("#achternaam", SqlDbType.VarChar){Value = achternaam});
command.Parameters.Add(new SqlParameter("#title", SqlDbType.VarChar){Value = title});
con.Open();
command.ExecuteNonQuery();
}
Perhaps one of your values is ');
That would terminate the INSERT statement early, and cause the error.
|
V
INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');
You should use SqlParameters instead of string concatenation.
Are you using TextBoxes? I can't tell for sure. Try something like this, and change to suit your specific needs.
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
try
{
string query = "insert into UserDetail(Name,Address)
values('" + txtName.Text + "','" + txtAddress.Text + "');";
SqlDataAdapter da = new SqlDataAdapter(query, con);
con.Open();
da.SelectCommand.ExecuteNonQuery();
con.Close();
lblmessage.Text = "Data saved successfully.";
}
catch
{
con.Close();
lblmessage.Text = "Error while saving data.";
}
}

Cannot Select Between No error can someonehelp me check string?

i want to input date value in textbox1 and textbox2 but i think im not sure about string cmd can someone help me check issuse ? please
try
{
con = new SqlConnection(MyConnectionString);
con.Open();
int tp;
string sqlstr = "select * from viewReC_store where stk_date_time between '" + TextBox1.Text + "' and '" + TextBox2.Text + "'";
cmd = new SqlCommand(sqlstr, con);
SqlDataReader sdr = cmd.ExecuteReader();
GridView1.DataSource = sdr;
GridView1.DataBind();
}
catch (Exception ex)
{
Label4.Text = "ERROR"+ex ;
}
con.Close();
Blockquote string sqlstr = "select * from viewReC_store where stk_date_time between '" + TextBox1.Text + "' and '" + TextBox2.Text + "'";
i guess this line
ok im got it
string sqlstr = "select * from viewReC_storeFG where stk_date_time between '" + TextBox1.Text + "' and '" + TextBox2.Text + "'";
thank u for read and reply
close..

SQL query for update statement in (C#)

I am new to the C# programming. Facing the problem Incorrect syntax near 'First_Name'.! in the given below code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=HP\SQLEXPRESS100;Database=CD_Gallery;Integrated Security=true";
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("update Customer_Info First_Name ='" + fname.Text + "'");
//'" + fname.Text.ToString() + "','" + lname.Text.ToString() + "','" + landmark.Text.ToString() + "','" + address.Text.ToString() + "','" + contact.Text.ToString() + "','" + email.Text.ToString() + "','" + dateTimePicker1.Text.ToString() + "','" + deposite.Text.ToString() + "')", con);
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("You Have Successfully Updated");
Custid.Text = "";
fname.Text = "";
lname.Text = "";
address.Text = "";
contact.Text = "";
email.Text = "";
landmark.Text = "";
deposite.Text = "";
}
}
}
Problem : You forgot to add word SET after your table name in update statement.
Solution1 : Add the word SET after table name in Update query (Don't Recommend this)
"update Customer_Info SET First_Name ='" + fname.Text + "'"
Warning : Your query is open to sql injection attacks.please use parameterised queries to avoid them
Solution 2: Using Parameterised Queries
Replace This:
SqlCommand cmd = new SqlCommand("update Customer_Info SET First_Name
='"+fname.Text+"'");
With This:
SqlCommand cmd = new SqlCommand("update Customer_Info First_Name = #fname");
cmd.Parameters.AddWithValue("#fname" , fname.Text);
Your problem not in C#, in SQL syntax (you miss set keyword)
SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");
you are missing SET keyword:
update Customer_Info SET First_Name ='" + fname.Text + "'"
and also provide where clause otherwise it will update all the records in your table.
You are missing set keyword in query you have to place set like this
SqlCommand cmd = new SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");

SQL code for delete Row?

please anyone to explain me what is the problem with following code why didn't delete Table Row.
con.Open();
SqlCommand cmd = new SqlCommand("delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' )", con);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = "succsess";
}
else
{
Message = "!";
}
con.Close();
75% of all these types of problems would be fixed if people loaded their queries into a string variable first then printed them out for debugging purposes :-)
You have a closing parenthesis ) at the end of your query which shouldn't be there.
your sql appears to have a closing brace in it without having an opening brace.
change it to
SqlCommand cmd = new SqlCommand(
"delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "'"
, con);
your command is:
SqlCommand cmd = new SqlCommand(
"delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' )",
con
);
while it should be:
SqlCommand cmd = new SqlCommand(
"delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' ",
con
);
(you should remove the ")" from your command)
Change row with sql command creation to this:
/* look at this - no need to wrap string values with
apostrophes since you use parameters */
string query = "delete from RentTable where CID = #id and MID = #mid";
/* create command */
SqlCommand cmd = new SqlCommand(query);
/* set parameters */
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.AddWithValue("#mid", MID);
This's not only solve your problem. This'll help you to prevent problems like it in the future if you'll be using parameters instead concatenation.
PS. Also you have "succsess" misspelled if english word was meant ;)

Categories