SQL update statement in C# - c#

I have table "Student"
P_ID LastName FirstName Address City
1 Hansen Ola
2 Svendson Tove
3 Petterson Kari
4 Nilsen Johan
...and so on
How do I change edit code in C#
string firstName = "Ola";
string lastName ="Hansen";
string address = "ABC";
string city = "Salzburg";
string connectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["LocalDB"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO Student (LastName, FirstName, Address, City)
VALUES (#ln, #fn, #add, #cit)";
command.Parameters.AddWithValue("#ln", lastName);
command.Parameters.AddWithValue("#fn", firstName);
command.Parameters.AddWithValue("#add", address);
command.Parameters.AddWithValue("#cit", city);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
To edit entry where Lastname field has lastname value and FirstName field has firstname value.
I don't want to use like this
UPDATE Persons SET Address = 'Nissestien 67', City = 'Sandnes'
WHERE LastName = 'Tjessem' AND FirstName='Jakob'
and I edited my original statement to
command.CommandText = "UPDATE Student(LastName, FirstName, Address, City)
VALUES (#ln, #fn, #add, #cit) WHERE LastName='" + lastName +
"' AND FirstName='" + firstName+"'";
But the statement is not getting executed. Why is it throwing SQL exception? Is there any solution to it?

This is not a correct method of updating record in SQL:
command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) VALUES (#ln, #fn, #add, #cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'";
You should write it like this:
command.CommandText = "UPDATE Student
SET Address = #add, City = #cit Where FirstName = #fn and LastName = #add";
Then you add the parameters same as you added them for the insert operation.

I dont want to use like this
That is the syntax for Update statement in SQL, you have to use that syntax otherwise you will get the exception.
command.Text = "UPDATE Student SET Address = #add, City = #cit Where FirstName = #fn AND LastName = #ln";
and then add your parameters accordingly.
command.Parameters.AddWithValue("#ln", lastName);
command.Parameters.AddWithValue("#fn", firstName);
command.Parameters.AddWithValue("#add", address);
command.Parameters.AddWithValue("#cit", city);

string constr = #"Data Source=(LocalDB)\v11.0;Initial Catalog=Bank;Integrated Security=True;Pooling=False";
SqlConnection con = new SqlConnection(constr);
DataSet ds = new DataSet();
con.Open();
SqlCommand cmd = new SqlCommand(" UPDATE Account SET name = Aleesha, CID = 24 Where name =Areeba and CID =11 )";
cmd.ExecuteNonQuery();

If you don't want to use the SQL syntax (which you are forced to), then switch to a framework like Entity Framework or Linq-to-SQL where you don't write the SQL statements yourself.

There is always a proper syntax for every language. Similarly SQL(Structured Query Language) has also specific syntax for update query which we have to follow if we want to use update query. Otherwise it will not give the expected results.

Please, never use this concat form:
String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
+ "WHERE supplier_id = " + textBox1.Text;
use:
command.Parameters.AddWithValue("#attribute", value);
Always work object oriented
Edit: This is because when you parameterize your updates it helps prevent SQL injection.

command.Text = "UPDATE Student
SET Address = #add, City = #cit
Where FirstName = #fn and LastName = #add";

private void button4_Click(object sender, EventArgs e)
{
String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("刪除成功");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button6_Click(object sender, EventArgs e)
{
String st = "SELECT * FROM suppliers";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
SqlDataReader reader = sqlcom.ExecuteReader();
DataTable datatable = new DataTable();
datatable.Load(reader);
dataGridView1.DataSource = datatable;
//MessageBox.Show("LEFT OUTER成功");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}

If you are using EF Core, then you can use FromSqlRaw
Here is an example.
Using Robin's update string, just add SELECT STATEMENT at the end.
String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
+ "WHERE supplier_id = " + textBox1.Text; SELECT Id From supplier WHERE supplier_Id ="+ textBox1,Text
var updatedSupplier = context.Supplier.FromSqlRaw(st).ToList();
(Please note this is using EF Core, Data table has Id column)

String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
+ "WHERE supplier_id = " + textBox1.Text;
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("update successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}

Related

sqlreader reading wrong column

Im trying to get the unique id from my persons table but the reader keeps trying getting the FirstName column and trying to convert that instead. at least thats what i think is happening
dataAdapter.SelectCommand = new SqlCommand("SELECT ID FROM Persons WHERE FirstName = " + txtBoxFirst.Text.ToString() + " AND LastName = " + txtBoxLast.Text.ToString()
, sqlConnection);
sqlConnection.Open();
SqlDataReader read = dataAdapter.SelectCommand.ExecuteReader();
while (read.Read())
{
pID = (Int32.Parse(read["ID"].ToString()));
}
read.Close();
sqlConnection.Close();
The error shows as
System.Data.SqlClient.SqlException:'Conversion failed when converting the varchar value 'First' to data type int.'
First, you miss the ' single-quote in your query so your parameter willn't be a string.
so it might be like
"SELECT ID FROM Persons WHERE FirstName = '" + txtBoxFirst.Text.ToString() + "' AND LastName = '" + txtBoxLast.Text.ToString() + "'"
But There is a big issue than it is SQL-Injection.
I would suggest you use parameters instead of connected SQL statement string.
make sure your parameter data type size as same as your table schema.
string sqlQuery = "SELECT ID FROM Persons WHERE FirstName = #FirstName AND LastName = #LastName";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
command.Parameters.Add("#FirstName", SqlDbType.VarChar,100).Value = txtBoxFirst.Text;
command.Parameters.Add("#LastName", SqlDbType.VarChar, 100).Value = txtBoxLast.Text;
SqlDataReader read = dataAdapter.SelectCommand.ExecuteReader();
while (read.Read())
{
pID = (Int32.Parse(read["ID"].ToString()));
}
}

How do I check Duplicate [duplicate]

This question already has an answer here:
how to i search if there is a same id in a database?
(1 answer)
Closed 6 years ago.
private void Add_Box_Click(object sender, EventArgs e)
{
string phoneNumber;
if (string.IsNullOrWhiteSpace(Id_Box.Text))// To check if the Id_box is empty or not
{
MessageBox.Show("Please Enter Your ID");// need to enter ID in order to save data
}
///////////////////////////////////////////check the Extension Box////////////////////////////////////////////////////////////////////////////////////
else
{
if (string.IsNullOrWhiteSpace(Ext_Box.Text))
{
phoneNumber = Phone_Box.Text;// if it is empty then it will only show the phone number
}
else
{
phoneNumber = Phone_Box.Text + "," + Ext_Box.Text; // show the phone number and the extension if there is something in the extension
}
///////////////////////////////////////////////////////////Save it to the Database///////////////////////////////////////////////////////
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Contact_List(Id, Name, Adress1, Adress2, City, Province, Postal_Code, Phone, Email)VALUES('" + Id_Box.Text + "','" + Name_Box.Text + "','" + Adress1_Box.Text + "','" + Adress2_Box.Text + "','" + City_Box.Text + "','" + Province_Box.Text + "','" + Code_Box.Text + "','" + phoneNumber + "','" + Email_Box.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Information Added", "Confirm");
/////////////////////////////////////Show new set of data after insert a new data/////////////////////////////////////////////////////////////
SqlCeCommand cmd2 = new SqlCeCommand("Select * from Contact_List;", con);
try
{
SqlCeDataAdapter sda = new SqlCeDataAdapter();
sda.SelectCommand = cmd2;
DataTable dt = new DataTable();
sda.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
sda.Update(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
////////////////////////////////Empty The Box/////////////////////////////////////////////////////////////////////////////////////////////////
Id_Box.Text = String.Empty;
Name_Box.Text = String.Empty;
Adress1_Box.Text = String.Empty;
Adress2_Box.Text = String.Empty;
City_Box.Text = String.Empty;
Province_Box.Text = String.Empty;
Code_Box.Text = String.Empty;
Phone_Box.Text = String.Empty;
Ext_Box.Text = String.Empty;
Email_Box.Text = String.Empty;
}
}
This code will store Id, name, etc to the database. But when there is a same Id, i want to delete it. When i delete it both of the same Id will be deleted and i don't want that so is there anyway to check duplicate before it store it to the database?
I want to do something like this if possible :
if ( the values in id column == to the Id_textBox) {
MessageBox.Show("Duplicate ,PLease enter anotherId")
}
Possible?
Before executing your INSERT SQL statement, try running the SQL int ContactCount = (int)cmd.ExecuteScalar("SELECT COUNT(*) FROM CONTACT_LIST WHERE Id = '" + Id_Box.Text + "'")
If ContactCount > 0 then you can do the DELETE your suggesting.
Can I also recommend that you use a SQL UPDATE instead of DELETEing and INSERTing the same record.
Also, read-up on SQL Injection attacks. Building a SQL statement, like you're doing here, using the values input by a user leaves you exposed to that type of vulnerability.
First of all, like in all these answers: Don't use string concatenation but parametrized queries to prevent SQL-injection.
For your problem:
You can either do a
string query = "SELECT count(*) from ContactList Where id = #id";
SqlCeCommand cmd = new SqlCeCommand(query, connection);
cmd.Parameters.Add("#id", SqlDbType.NVarChar, 50).Value = Id_Box.Text;
int count = (int)cmd.ExecuteScalar();
if count > 0 the id already exists.
Or you can do a
string query "IF NOT EXISTS(SELECT count(*) from ContactList Where id = #id) INSERT INTO ContactList(Id, ...) VALUES(#id, ...)";
SqlCeCommand cmd = new SqlCeCommand(query, connection);
cmd.Parameters.Add("#id", SqlDbType.NVarChar, 50).Value = Id_Box.Text;
int count = cmd.ExecuteNonQuery();
count will then contain the number of rows affected, ie 0 if the value already existed, or 1 if it did not exist, but was newly inserted.

Checking if a user exists, and stopping a database insert (access database)

I just don't know how to check if the users exists in the database and stop it from inserting a new row to the db (which will cause an error as I set the user to be a primary key)
protected void Button1_Click1(object sender, EventArgs e)
{
{
OleDbConnection myconnection = new OleDbConnection();
myconnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Event.mdb";
myconnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myconnection;
myCommand.CommandType = CommandType.Text;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
myCommand.CommandText = query;
try
{
int amountOfUsers = (int)myCommand.ExecuteScalar();
if (amountOfUsers < 1)
{
String myQuery = "insert into users (uname,upassword,email,type) Values ('" + UserName.Text + "','" + Password.Text + "' ,'" + Email.Text + "',' user');";
myCommand.CommandText = myQuery;
myCommand.ExecuteNonQuery();
Label1.Text = "user registered";
}
else
{
Label1.Text = "user already exists";
UserName.Text = "";
Email.Text = "";
}
}
finally
{
myconnection.Close();
}
}
}
correct your query:
query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'" ,UserName.Text );
Your question isn't clear at all but I can suggest a few things..
First of all, I think you forget to use your uname as a second parameter in your:
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
line. You used {0} but never point any value to this parameter. (I assume you don't have a username called {0}) Like;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'", UserName.Text);
As a second, please always use parameterized queries. This kind of string concatenations are open for SQL Injection attakcs.
Like;
String myQuery = "insert into users (uname,upassword,email,type) Values (#uname, #upassword, #email, #type)";
OleDbCommand myCommand = new OleDbCommand(myQuery);
myCommand.Parameters.AddWithValue("#uname", UserName.Text);
myCommand.Parameters.AddWithValue("#upassword", Password.Text);
myCommand.Parameters.AddWithValue("#uname", Email.Text);
myCommand.Parameters.AddWithValue("#uname", "user");
i want to check if the username in UserName.Text is availble in the
data base or no and if it does i want to stop from inserting new data
Than you should use SELECT first to check your username is exist in your database or not like;
string query = string.Format("SELECT * FROM users WHERE uname = '{0}'", UserName.Text);
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
SqlDataReader reader = myCommand.ExecuteReader();
if(reader.HasRows)
{
//Your username exist in your database
}
else
{
//Doesn't exist
}
you have missing the parameter uname , you have pass the text of UserName textbox to uname
for eg
"SELECT COUNT(*) FROM users WHERE uname='" + UserName.Text +"'

Using while loop for sqldatareader

I trying to get both policeid and fullname from my table named PoliceAccount when the handle column equal to the value of the dropdownlist and then put the value into a label and display it. By using the code provided below I keep getting the result of the last row data of policeid and fullname. However, my table contain of 2 police account which having the column handle equal to the value of the dropdownlist. Do help me out. THANKS!
conn.Open();
sql = "Select policeid, fullname From PoliceAccount Where handle = '"+ ddlReportDateTime.SelectedValue +"'";
using (var cmd2 = new SqlCommand(sql, conn))
{
SqlDataReader dr;
dr = cmd2.ExecuteReader();
while (dr.Read())
{
String policeid = dr.GetString(0);
String fullname = dr.GetString(1);
String result = policeid + " " + fullname;
lblAssignTo.Text = result;
}
}
conn.Close();
you got to put the value into a collection (list or so):
var myData = new List<string>();
while (dr.Read())
{
String policeid = dr.GetString(0);
String fullname = dr.GetString(1);
String result = policeid + " " + fullname;
myData.Add(result);
}
and then use it as you want - display the first/last/concatenated/etc....
EDIT:
display the concatenated string:
yourLabel.Text = myData.Aggregate((x,y)=> x + "; " + y);

i need to get more than one value from database sql

I need to get 6 values from database and bind them to link button texts her is the code
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string post = Request.QueryString["post"];
////string title = "nokia";
string date = DateTime.Now.ToShortDateString();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\nokiaoaq\Desktop\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
try
{
conn.Open();
//string str = "insert into Table1 (title , date_ ,www, cat) values (' " + TextBox1.Text + "','" + DateTime.Now.ToShortDateString() + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Text + "')";
////string str = "INSERT INTO Table1 (title,date_,www ) values ('ddddddd','aaaaaaa','qqqqqq')";
string str =
//"SELECT from table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee";
"SELECT table1.title FROM table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee DESC";
SqlCommand objcmd = new SqlCommand(str, conn);
SqlDataAdapter da1 = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
da1.Fill(dt);
//DataRow dr = new DataRow();
//DataRow dr = ds.Tables[0].Rows[0];
foreach (DataRow dr in dt.Rows)
{
ml1.Text = dr[0].ToString();
ml2.Text = dr[1].ToString();
ml3.Text = dr[2].ToString();
ml4.Text = dr[3].ToString();
ml5.Text = dr[4].ToString();
ml6.Text = dr[5].ToString();
}
}
catch (Exception ex)
{
Label4.Text = "Failed to connect to data source";
}
finally
{
conn.Close();
}
}
}
ml is link button id
You are trying to assign 6 fields from the row returned to 6 different textboxes, but your select query asks for just one field. If you want more than one field returned then add their names to the select query (change fieldX to the appropriate field name).
string str = "SELECT title, field1, field2, field3, field4, field5 " +
"FROM table1 WHERE cat = 1 and datee=#dt ORDER BY datee DESC";
also do not use string concatenation to build the sql statement. Use always a parametrized query
SqlCommand objcmd = new SqlCommand(str, conn);
objcmd.Parameters.AddWithValue("#dt", datee);
.....
this will avoid problem with formatting strings, date, numbers etc, but also the sql injection problem.
By the way, I hope that your code returns just one row because, as it stands now, if you have more than one row returned then only the one with the earliest date will be shown in the textboxes. (And if this is the case then the order by is useless). If you have more than one row returned then you should consider to bind the datatable to a GridView to show all records returned.

Categories