I am currently writing a Search function that bring down a value Name
Here is my query:
"SELECT Company.Name, Company.Reg FROM Company WHERE Name LIKE '%''" + Name + "''%'";
Here is the function:
public object CompanySearch(string Name)
{
using (PCE)
{
SqlConnection con = new SqlConnection(constr);
try
{
List<CompanySearch> cm = new List<CompanySearch>();
SqlCommand command = new SqlCommand();
command.Connection = con;
"SELECT Company.Name, Company.Reg FROM Company WHERE Name LIKE '%''" + Name + "''%'";
con.Open();
//process the sql execute etc
}
}
}
Is the way I reading Name correctly?
I tested without ' ' , however I get an exception message as follow:
"ExceptionMessage": "Incorrect syntax near 'Mysearch'.",
UPDATE
SELECT Company.Name, Company.Reg
FROM Company
WHERE CompanyName LIKE '%MySearch%';
This is the code that I execute in SSMS, and it went sucess.
However it doesnt work on my C#
First of all, you should always avoid to "manually build" your own query. This is the best way to have SQL Injection (https://en.wikipedia.org/wiki/SQL_injection)
Secondary, you should used Parameter in your query
SqlCommand cmd = new SqlCommand("SELECT Company.Name, Company.Reg WHERE Name LIKE #companyName", connection);
cmd.Parameters.Add("#companyName", SqlDbType.NVarChar).Value = Name;
But in 2020, you should use an ORM instead of building your own query. This is far better to save time and avoid bugs.
Have a look at EF Core (https://learn.microsoft.com/fr-fr/ef/) or Dapper (https://stackexchange.github.io/Dapper/), ...
This is what I try, it worked for me...
public object CompanySearch(string Name)
{
SqlConnection con = new SqlConnection(constr);
try
{
List<CompanySearch> cs = new List<CompanySearch>();
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText = "SELECT Name, Reg, FROM Company WHERE Name LIKE '%" + Name + "%'";
con.Open();
//process the sql execute etc
}
}
}
However, a good practice is to parameterize your query that mentioned by #HoneyBadger
Related
I'm a beginner in SQL and c#. I'm trying to create a system that will lead the user to eligibility form if they have not done it before, but an error that says invalid column name keeps popping.
string query = "select * from Eligibility where Name = " + textBox1.Text;
sql.Open();
SqlCommand cmd = new SqlCommand(query, sql);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
label6.Text = (dr["name"].ToString());
}
sql.Dispose();
if (label6.Text == textBox1.Text)
{
this.Hide();
UserHomeView uhv = new UserHomeView();
uhv.Show();
}
else
{
this.Hide();
Eligibility eli = new Eligibility();
eli.Show();
}
You missed the single quotation
string query = "select * from Eligibility where Name = '" + textBox1.Text + "'";
Even so, there is some serious problem with the above code. This can cause a serious sql injection problem for you Check wikipedia entry on this
It's better to use the add parameters function which will sanitize the input and make it safe for you to execute the query.
The best solution would be something like this
string query = "select * from Eligibility where Name = #Name";
sql.Open();
SqlCommand cmd = new SqlCommand(query, sql);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = textBox1.Text;
This way, your query will be injection safe.
Just to build on what others have said:
Once you're comfy with doing things this way check out Stored Procedures.
Stored Procedures lets you save the query in the database and all you do on the c# side is call the Stored Procedure and add the required parameters.
These tend to be a better way of doing this as you can then learn about how to restrict access to your database for only certain users and also it means the Query itself is in an environment that will check for mistakes as well.
This is a good article as an introduction to them:
http://www.sqlservertutorial.net/sql-server-stored-procedures/
You can use Parameters of SqlCommand, like this:
string query = "select * from Eligibility where Name = #Name";
sql.Open();
SqlCommand cmd = new SqlCommand(query, sql);
cmd.Parameters.Add("#Name", SqlDbType.Text);
cmd.Parameters["#Name"].Value = textBox1.Text;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
label6.Text = (dr["name"].ToString());
}
sql.Dispose();
if (label6.Text == textBox1.Text)
{
this.Hide();
UserHomeView uhv = new UserHomeView();
uhv.Show();
}
else
{
this.Hide();
Eligibility eli = new Eligibility();
eli.Show();
}
I am trying to insert data into a database that I have that has a table called EmployeeInfo
The user is prompted to enter a last name and select a department ID (displayed to the user as either marketing or development) The column ID automatically increments.
Here is my Code behind
protected void SubmitEmployee_Click(object sender, EventArgs e)
{
var submittedEmployeeName = TextBox1.Text;
var submittedDepartment = selectEmployeeDepartment.Text;
if (submittedEmployeeName == "")
{
nameError.Text = "*Last name cannot be blank";
}
else
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("ConnString");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO EmployeeInfo (LastName, DepartmentID ) VALUES ('" + submittedEmployeeName + "', " + submittedDepartment + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
The error I'm recieving is 'Arguement exception was unhandled by user code'
Here is a picture of it.
As requested. More details
If I had enough reputation, I would rather post this as a reply, but it might actually be the solution.
The reason why it stops there is because you are not providing a legit SqlConnection, since your input is: "ConnString", which is just that text.
The connection string should look something like:
const string MyConnectionString = "SERVER=localhost;DATABASE=DbName;UID=userID;PWD=userPW;"
Which in your case should end up like:
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(MyConnectionString);
Besides that, you should build your connections like following:
using (SqlConnection con = new SqlConnection(MyConnectionString)) {
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = xxxxxx; // Your query to the database
cmd.Connection = con;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
This will do the closing for you and it also makes it easier for you to nestle connections. I did a project recently and did the connection your way, which ended up not working when I wanted to do more than one execute in one function. Just important to make a new command for each execute.
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)
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE(ID= '" +
txtStudentIDnumber.Text + "')";
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
In your command text you need to remove single quotes (') around the txtStudentIDnumber.Text as it appears ID is of type integer and you are passing it as string. Following should fix the error.
system.CommandText = "DELETE FROM Student WHERE(ID= " + txtStudentIDnumber.Text + ")";
EDIT: With respect to #mdb comments, you should always use Parameters in your query so that you can avoid SQL Injection. Consider the following:
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID = ?";
OleDbParameter parameter = new OleDbParameter("ID", txtStudentIDnumber.Text);
system.Parameters.Add(parameter);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID=#ID";
system.Parameters.AddWithValue("#ID", txtStudentIDnumber.Text);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
What will happen when user input for txtStudentIDNumber is,
1 or 1=1
In that case hardcoded SQL string will be,
DELETE FROM Student WHERE(ID=1 or 1=1)
So prefer parameterized sql statement instead of hard-coded string.
using(OleDbConnection cn=new OleDbConnection(cnStr))
{
using(OleDbCommand cmd=new OleDbCommand())
{
cmd.CommandText="DELETE FROM Student WHERE ID=#ID";
cmd.Connection=cn;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value=txtStudentIDnumber.Text;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
I want to use a select statement to find if there is a record that already exists. I've put the code below but it throws an error at the dReader = comm.ExecuteReader(); and i'm unsure why. Any help?
string connString = "Data Source=KIMMY-MSI\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID == " + txtID.Text;
comm.Connection.Open();
dReader = comm.ExecuteReader();
if (dReader.HasRows == true)
{
Response.Write("Exists");
}
The error:
Invalid Column Name (whatever I input)
It seems to be looking for a column named what I input rather than looking for the actual data.
Change your == to =. That is invalid SQL as it is.
Also if txtID.Text is non-numeric then it needs to be in single quotes. You should not be constructing your SQL like this, instead use a parameter:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = #CustomerID";
comm.Parameters.AddWithValue("CustomerID", txtID.Text);
More Info
C# using statement
SQL reference
SQL injection (why you should parameterize your queries)
It looks like your command has an issue:
SELECT * FROM Customers WHERE CustomerID == 1
In SQL you don't need to use the == operator to ensure something is equal to another.
Try:
SELECT * FROM Customers WHERE CustomerID = 1
In addition, you might want to read up about SQL Injection, the way you are binding the value is directly from a textbox value. This has a huge security hole which could lead to arbitrary sql command execution.
Change this line:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID == " + txtID.Text;
To this line:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = #id";
comm.Parameters.AddWithValue("id", int.Parse(txtID.Text));
Assuming that your customer id is int on the database.
The equals operator in SQL is just a single =.
Also, you really shouldn't be concatenating SQL queries like that, you are just opening yourself up to SQL Injection attack. So change it to be like this:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = #CustomerId";
comm.Parameters.AddWithValue("#CustomerId", txtID.Text);
See Stop SQL Injection Attacks Before They Stop You on MSDN.
You are using invalid SQL. You name to change "==" to "=".
You should also consider wrapping your IDisposable objects in using statements so that unmanaged objects are properly disposed of and connections are properly closed.
Finally, think about using parameters in your SQL, instead of concatenating strings, to avoid SQL injection attacks:
string connString = #"Data Source=KIMMY-MSI\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
string sql = "SELECT * FROM Customers WHERE CustomerID = #CustomerID";
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand comm = new SqlCommand(sql, conn))
{
comm.Connection.Open();
comm.Parameters.AddWithValue("#CustomerID", txtID.Text);
using (SqlDataReader dReader = comm.ExecuteReader())
{
if (dReader.HasRows == true)
{
Response.Write("Exists");
}
}
}