sqlreader reading wrong column - c#

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()));
}
}

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.' on Datatable and object

I've looked at a lot of similar questions on this site and elsewhere but none of them have helped me.
I'm trying to make a database connection with a query but I get the error
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
on 2 different lines of code. I've tried to use spaces in the query around the = but that doesn't help.
Code 1 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NChar).Value = attackCategory;
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM attackCategory = #attackCategory WHERE TaughtOn = #taughtOn";
using (SqlDataAdapter sda = new SqlDataAdapter(select.CommandText, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
The exception is thrown on the sda.Fill(dt); line of code. This code works if no parameters are used in the query:
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
And code 2 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NVarChar).Value = attackCategory;
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Name FROM attackCategory = #attackCategory WHERE ID = #ID";
connection.Open();
object name = select.ExecuteScalar();
connection.Close();
return name;
The exception fires on the object name = select.ExecuteScalar(); line of code. This code works if 1 parameter is used in the query:
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Inhabitants FROM Planet WHERE ID=#ID";
You cannot provide table name has parameter, parameter applies in where clause with columns value.
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
but, we need to simplify to use parameter in this query.
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#taughtOn", SqlDbType.VarChar,50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
In the above tsql query, string concatenation applies and table name is included in the string, which will work.
Edit:-
I get it why you the sqlDataAdapter is not Recognizing the parameter.
Reason is you have not provided it. Yes, That's right you have provided the CommandText and not the Command Object which is of select variable.
I have corrected your code.
select.Parameters.Add("#taughtOn", SqlDbType.VarChar, 50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
select.Connection = new SqlConnection("provide your sql string");
using (SqlDataAdapter sda = new SqlDataAdapter(select))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Hope this helps !!
You can't bind object names like that. For object names, you'll have to resort to some sort of string concatenation. E.g.:
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM " + attackCategory + " WHERE TaughtOn=#taughtOn";
Note:
This is an over-simplified solution that does nothing to mitigate the risk of SQL-Injection attacks. You'll need to sanitize attackCategory before using it like this.

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.

SQL update statement in 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);
}

How to make a filtration by a parameter in CommandText in C#?

I would like to fill a ComboBox but I want to sort data by one parameter called “id_group”.
I wrote a code but it does not work.
In this line happens an exception which says “incorrect syntax” :
SqlDataReader sd = sc.ExecuteReader();
This is all my code:
int id_group=5;
SqlConnection conn = new SqlConnection();
SqlCommand sc = conn.CreateCommand();
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP '" + id_group + "'";
conn.Open();
SqlDataReader sd = sc.ExecuteReader(); //this happens exception - "incorrect syntax"
while (sd.Read())
{
string graduate = (string)sd["STUDENT"];
Student_comboBox.Items.Add(graduate);
}
conn.Close();
How to make it work?
Is there other ways to filter data by a parameter?
actually you are missing = on your query, so this should looked like this,
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP = '" +
id_group + "'";
but please do parameterize it to avoid SQL Injection
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP = #groupID";
sc.Parameters.AddWithValue("#groupID", id_group);
SOURCE
AddWithValue
Add (recommended to use)

return student information - SQL/C# assignment

so essentially, I have two text fields, one with the firstName and one with the lastName of the student. What I want the program to do is this:
return the student's phone number and comments using the firstName and lastName from the TextBox above. This is what I have so far:
if (actionButton.Text == "Update")
{
SqlConnection cn;
cn = new SqlConnection();
cn.ConnectionString = "Data source=(local); Initial Catalog=INT422Assignment1; Integrated Security=SSPI;";
cn.Open();
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT firstName, lastName, phoneNumber, Comments FROM myTable WHERE firstName LIKE #firstName AND lastName LIKE #lastName"; //AND lastName LIKE #lastName"
//used this part to delete records
SqlParameter param = new SqlParameter();
param.ParameterName = "#firstName";
param.Direction = ParameterDirection.Input;
param.SqlDbType = SqlDbType.VarChar;
param.Value = firstNameTB.Text;
cmd.Parameters.Add(param);
param.ParameterName = "#lastName";
param.Direction = ParameterDirection.Input;
param.SqlDbType = SqlDbType.VarChar;
param.Value = lastNameTB.Text;
cmd.Parameters.Add(param);
//display data in a listbox
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
string s;
s = reader["firstName"].ToString() + "-" + reader["lastName"].ToString() + reader["phoneNumber"].ToString() + reader["Comments"].ToString();
MessageBox.Show(s);
}
cmd.ExecuteNonQuery();
cn.Close();
}
I'm not sure where to go from here. In the code I have placed two comment statements, so I have used the above in two different parts of my assignment, but when I bring them together, it doesn't work.
what is happening is that I am not getting any results. Essentially I need it to give me the phone number and comments of the student indicated in the two text boxes
I assume you're getting an error, yes? You are trying to do two operations on the same command object and my hazy recollection says that's not going to work. Try removing this line.
cmd.ExecuteNonQuery();
If you have studied the using statement, that's typically a better solution for handling resources like your connection and reader.
if (actionButton.Text == "Update")
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "Data source=(local); Initial Catalog=INT422Assignment1; Integrated Security=SSPI;";
cn.Open();
MessageBox.Show(cn.ConnectionState.ToString());
// If you are shown "Open" by above messagebox and you are using correct table and column names then you will get accurate results by following code
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT firstName, lastName, phoneNumber, Comments FROM myTable WHERE firstName LIKE '" + firstNameTB.Text + "' AND lastName LIKE '" + lastNameTB.Text + "' ";
SqlDataReader reader = cmd.ExecuteReader();
string s = "";
while (reader.Read())
{
s = reader["firstName"].ToString() + "-" + reader["lastName"].ToString() + reader["phoneNumber"].ToString() + reader["Comments"].ToString();
MessageBox.Show(s);
}
cn.Close();
}

Categories