SQL Server select query execution from c# - c#

string user = "1234";
string strSQL = string.Format("Select * From User where UserId = '{0}'",user);
SqlCommand myCommand = new SqlCommand(strSQL, cnn);
reader = myCommand.ExecuteReader();
My User table consists of UserId and Password columns. The UserId column type is nchar and so I've used the single quotes. I get an error saying that
incorrect syntax near the keyword User"
(I guess the table name User is being referred to here).
I have the connection string and other database environment related things correctly for I've checked the database connection status and it is open(during program execution).
What is the error in the syntax? I'm unable to retrieve the rows from my table.

User is a Keyword. Use square bracket around it to avoid the error. Select * from [User]
string strSQL = string.Format("Select * From [User] where UserId = '{0}'",user);
Also, you should always use parameterized query like below to prevent SQL Injection attack:
string strSQL = string.Format("Select * From [User] where UserId = #UserId");

You should really use parameters for this:
string user = "1234";
using (SqlCommand command = new SqlCommand("select * from [User] where UserId = #userid", cnn))
{
command.Parameters.AddWithValue("#userid", user);
using (SqlDataReader reader = myCommand.ExecuteReader())
{
// iterate your results here
}
}
Well spotted by other posters, I never caught the reserved word thing with your table name. I've amended my answer - but can't take credit for missing the obvious!

you should wrap user with brackets []
string strSQL = string.Format("Select * From [User] where UserId = '{0}'",user);
The query above is vulnerable to SQL Injection. It should be parameterized to avoid this. The following is an example:
string user = "1234";
string strSQL = "Select * From [User] where UserId = #userID";
SqlCommand myCommand = new SqlCommand(strSQL, cnn);
myCommand.AddWithValue("#userID", user);
reader = myCommand.ExecuteReader();
use the following
Try-Catch block for proper catching of errors
using statement for proper object disposal
snippet:
string user = "1234";
string strSQL = "Select * From [User] where UserId = #userID";
using (SqlConnection cnn = new SqlConnection("connection string here"))
{
using (SqlCommand myCommand = new SqlCommand(strSQL, cnn))
{
myCommand.Parameters.AddWithValue("#userID", user);
using (SqlDataReader reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["columnName"].ToString());
}
}
}
}

Wrap with []. It is a keyword. Read Reserved Keywords article from MSDN.
string strSQL = string.Format("Select * From [User] where UserId = '{0}'",user);
But more important part, your query is open for an SQL Injection attack. You should always use parameterized queries.
string strSQL = "Select * From [User] where UserId = #userID";
SqlCommand myCommand = new SqlCommand(strSQL, cnn);
myCommand.Parameters.AddWithValue("#userID", user);

Related

How to Display data on a Label using MS Access Database in C#

I tried to get the balance and customer name to show up on the labels by getting user's input the customers ID on textbox1. But every time i tried to input the ID even just the first digit of the ID, it already shows error "Data type mismatch in criteria expression".
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
string sql = "SELECT * FROM Customer WHERE ID= '" +textBox1.Text+ "'";
cmd.CommandText = sql;
OleDbDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
labelbalance.Text = reader["Balance"].ToString();
labelname.Text = reader["Firstname"].ToString() + reader["Lastname"].ToString();
}
Remove the single quotes around Id:
string sql = "SELECT * FROM Customer WHERE ID= " + textBox1.Text;
Because you have the quotes, ID is interpreted as character.
Update
As suggested in the comment, rather use parametrized query and avoid sql injection:
string sql = "SELECT * FROM Customer WHERE ID= #var";
cmd.CommandText = sql;
cmd.Parameters.Add(new OleDbParameter("#var", int.Parse(textBox1.Text));

Adding a Where Clause to a OleDbCommand

I am trying to add a where clause to the following line of code.
the reason for this is because i get the datatable from a dropdown combobox. now i want to filter that table on user name, so that only the user can see their records.
i need help on how to write the where clause into this code.
if you need any more information i will gladding add it.
thank you for any help.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ", comboBox1.Text), con);
After Comments
i added the sql injection protection.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From
#Companydetails where Research_ID = #Researcher_ID"), con);
cmd.Parameters.AddWithValue("#Companydetails", comboBox1.Text);
cmd.Parameters.AddWithValue("#Researcher_ID", usernumber_lab.Text);
but now it is giving me a error saying:
Additional information: Syntax error in query. Incomplete query clause.
is there something else i need to add to finnish this query off?
I would do it as follows;
string query = "Select * from MyTable Where username = #username";
using (OleDbCommand cmd = new OleDbCommand(query, con))
{
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = comboBox1.Text;
}
This way the object will dispose automatically and also you'll be safe from Sql Injection
Please try this
string sql = String.format("Select * From {0} where id = {1}", comboBox1.Text, id);
OleDbCommand cmd = new OleDbCommand(sql,con);
You can just make your sql statement longer:
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From table Where something = something", comboBox1.Text), con);
You don't have to work with multiline or anything. This is only needed in some database managers, but not in a c# sql statement.
If you would like
OleDbCommand cmd = new OleDbCommand(String.Format("Select * From {0} WHERE username='{1}'", comboBox1.Text,username.Text), con);
You can try the below code
OleDbCommand cmd = new OleDbCommand(string.Format(
"SELECT * FROM {0} WHERE Username = '{1}'",
comboBox1.Text, userName), con);

Whats wrong with my MS Access Update Query?

Here is my Query:
string Select = "Update DC set Password = '" + txtPass.Text + "' WHERE ID ="+Convert.ToInt32(cbxDocs.SelectedIndex + 1);
con = new OleDbConnection();
this.readconfile = new ReadConfigFile();
con.ConnectionString = this.readconfile.ConfigString(ConfigFiles.ProjectConfigFile);
con.Open();
cmd = new OleDbCommand(Select, con);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
I don't know what is wrong but it gives me an error message that "Syntax error in UPDATE STATEMENT".
I have two fields in my table 'DC' ID and Password, nothing else.
PASSWORD is reserve word enclose it in square brackets like [Password], so your query should start like:
"Update DC set [Password]....
Consider using parameterized query, this will save you from Sql Injection
I think u don't need the ' on ur query and Password is reserved in almost every ddb.
And you could use parameters to avoid the concat with the +
Ex.
string pass = TxtPass.Text;
int s = cbxDocs.SelectedIndex+1;
string Select = "Update DC set Password = #a WHERE ID = #o";
OleDbCommand cmd = new OleDbCommand(Select, conn);
cmd.Paramaters.AddWithValue("#a", pass);
cmd.Parameters.AddWithValue("#o", s);
//everything else....

Unable to execute cmd.ExecuteReader()

Here is the code where i'm trying to retrieve user name using emailid.
string query="select name from userdetails where emailid=" + email + ";" ;
connection.Open();
MySqlCommand cmd = new MySqlCommand(query,connection);
MySqlDataReader rd = cmd.ExecuteReader();
while(rd.Read())
{
uname = (string)rd["emailid"];
return uname;
}
parameterized the value to avoid from SQL Injection
string query="select name from userdetails where emailid=#email" ;
MySqlCommand cmd = new MySqlCommand(query,connection);
cmd.Parameters.AddWithValue("#email", email);
Try this code snippet:
string connStr = "connection string here";
string sqlStatement = "select name from userdetails where emailid=#email";
using (MySqlConnection conn = new MySqlConnection(connStr))
{
using(MySqlCommand comm = new MySqlCommand())
{
comm.Connection = conn;
comm.CommandText = sqlStatement;
comm.CommandType = CommandType.Text;
comm.Parameters.AddWithValue("#email", email);
try
{
conn.Open();
MySqlDataReader rd = cmd.ExecuteReader();
// other codes
}
catch(SqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}
For proper coding
use using statement for proper object disposal
use try-catch block to properly handle exception
Put you emailin sigle qoute because it is varchar like this..
string query="select name from userdetails where emailid='" + email + "';" ;
But this may cause SQL Injection...so use this...
string query="select name from userdetails where emailid=#email;" ;
MySqlCommand cmd = new MySqlCommand(query,connection);
cmd.Parameters.AddWithValue("#email",email);
Update your select query like this with adding email in single quote:
string query = "select name from userdetails where emailid='" + email +"';";
or
you can use parametrized query like this :
string query="select name from userdetails where emailid=#email" ;
MySqlCommand cmd = new MySqlCommand(query,connection);
cmd.Parameters.AddWithValue("#email", email);

C# - Web Site - SQL Select Statement

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

Categories