syntax error (comma) in query expression - c#

I'm trying to get the user's details from a database to show in some text boxes; however there seems to be a problem with my code. The following error keeps appearing:
syntax error (comma) in query expression
This is the complete code:
string filePath;
try
{
filePath = (Application.StartupPath + ("\\" + DBFile));
connection = new System.Data.OleDb.OleDbConnection((ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbDataReader reader;
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
// ---retrieve user's particulars---
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1);
reader = command.ExecuteReader(CommandBehavior.CloseConnection);
reader.Read();
// ---display user's particulars---
textBox2.Text = reader["SSN"].ToString();
textBox3.Text = reader["FirstName"].ToString();
textBox4.Text = reader["LastName"].ToString();
}

Here
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1);
so internally .ToString method would have been called on textBox1 and your commandText would have become
SELECT * FROM Enroll WHERE ID=System.Windows.Forms.TextBox, Text:
Hence the error.
What you probably mean is the text in the textbox
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1.Text);
Note:
You should not do it in the first place. You should consider using parameterized queries instead. So, what you should be doing is
SqlCommand cmd = new SqlCommand("SELECT * FROM Enroll WHERE ID=#ID");
cmd.Parameters.AddWithValue("#ID", textBox1.Text.Trim());

What about changing
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1);
to
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1.Text);

This will be more appropriate :
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1.text.toString()+"");

Related

two queries in same method

I am trying to execute two queries in the same method but it gives me this exception. I can get red of this exception by declaring new command but is there any way to use the same command?
string id="hi";
connection.Open();
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
string query1 = "select * from products where category='" + comboBox1.Text + "' and subcategory = '" + comboBox2.Text + "' and sizes='" + comboBox3.Text + "'";
command1.CommandText = query1;
OleDbDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
id = reader[0].ToString();
}
textBox1.Text = id;
string query = "insert into category_in (category_id,amount,amount_in) values ('"+ id+"' ,500,300)";
command1.CommandText = query;
command1.ExecuteNonQuery();
MessageBox.Show("saved");
connection.Close();
You need to close your OleDbDataReader object when you are finished with it:
// previous code omitted for brevity
//
while (reader.Read())
{
id = reader[0].ToString();
}
// need to close reader
//
reader.Close();
// run your other query (omitted for brevity)
And as the comment on your question states, the way you construct your query is extremely vulnerable to a SQL inject attack. Parameterize your query the proper way.
As per Dmitry's comment, I completely agree. Wrap your OleDbDataReader object in a using block to call OleDbDataReader.Dispose() upon completion of the block:
using (OleDbDataReader reader = command1.ExecuteReader())
{
// ...
}
You need to close the reader after first execution,so code will be like this
string id="hi";
connection.Open();
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
string query1 = "select * from products where category='" + comboBox1.Text + "' and subcategory = '" + comboBox2.Text + "' and sizes='" + comboBox3.Text + "'";
command1.CommandText = query1;
OleDbDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
id = reader[0].ToString();
}
textBox1.Text = id;
////////code for closing the reader/////////////
reader.Close();
///////////////
string query = "insert into category_in (category_id,amount,amount_in) values ('"+ id+"' ,500,300)";
command1.CommandText = query;
command1.ExecuteNonQuery();
MessageBox.Show("saved");
connection.Close();

Incorrect syntax near ' '

This is the page behind code where it have error
if (Session["username"] != null)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["registerCS"].ConnectionString;
string sql1 = "Select pemgrp from Profile where userID = '" + Session["username"].ToString() + "'";
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
DataTable dt = new DataTable();
cmd.CommandText = sql;
cmd.Connection = con;
//open connection and execute command
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
lb_classmates.Text = dr[0].ToString();
}
}
However, when i run, it give me this error :
Incorrect syntax near the keyword 'where'.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect
syntax near the keyword 'where'.
As you are using sub-query therefore this
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
should be
string sql = "Select studname from Profile where pemgrp in (" + sql1+ ")";
and you should be using Parametereized queries to avoid SQL injection.
I think It should be
string sql = "Select studname from Profile where pemgrp in (" + sql1+ ")";
instead of
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
I would strongly recommend you to use parametereized queries
No One's answer is of course right.
If you want to use a subquery in a query, you should use IN (Transact-SQL)
Determines whether a specified value matches any value in a subquery
or a list.
test_expression [ NOT ] IN
( subquery | expression [ ,...n ]
)
Also you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also consider to use using to dispose your SqlConnection.
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["registerCS"].ConnectionString))
{
connection.Open();
string sql1 = "Select pemgrp from Profile where userID = #username";
string sql = "Select studname from Profile where pemgrp IN (" + sql1 + ")";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#username", Session["username"].ToString());
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//
}
}
You should use parameterized query something llike this
string sql = "Select studname from Profile where pemgrp = #p1";
and to pass parameter
command.Parameters.AddWithValue("#p1",sql1);

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 +"'

how to use executereader to read one value

I want to read an int value from my table. but I faced with error
this is my code. please help me to edit my code.
sqlc = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
string username = HttpContext.Current.User.Identity.Name.ToString();
cmd.CommandText = #"SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username));
//string RemainedCharge;
sqlc.Open();
SqlDataReader rdr = cmd.ExecuteReader();
// loop over all rows returned by SqlDataReader
while(rdr.Read())
{
RemainedChargeLbl.Text=rdr.GetString(0);
}
To read one value you don't need reader. Use SqlCommand.ExecuteScalar Method which executes query and returns first column of the first row in result set returned by query:
int value = (int)cmd.ExecuteScalcar();
BTW it's better to create command object with sqlc.CreateCommand() - it creates appropriate command and automatically assigns connection to it.
You are not assigning connection object sqlc to the SqlCommand.
Add this:
cmd.Connection=sqlc;
Complete Solution:
sqlc = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection=sqlc;
string username = HttpContext.Current.User.Identity.Name.ToString();
cmd.CommandText = #"SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username));
//string RemainedCharge;
sqlc.Open();
RemainedChargeLbl.Text =((int) cmd.ExecuteScalar()).ToString();
Use this code:
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username);
cmd.Parameters.AddWithValue("#id", index);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
}

MySQL Password Login Code?

I'm trying to do a Login code in C# with MySQL. Basically the user enters a username and password then the code checks the database if the the password is correct. I'm having trouble getting the code to read from the data base... Here is where I'm at.
public string strUsername;
public string strPassword;
//Connect to DataBase
MySQLServer.Open();
//Check Login
MySqlDataReader mySQLReader = null;
MySqlCommand mySQLCommand = MySQLServer.CreateCommand();
mySQLCommand.CommandText = ("SELECT * FROM user_accounts WHERE username =" +strUsername);
mySQLReader = mySQLCommand.ExecuteReader();
while (mySQLReader.Read())
{
string TruePass = mySQLReader.GetString(1);
if (strPassword == TruePass)
{
blnCorrect = true;
//Get Player Data
}
}
MySQLServer.Close();
From what I've done in the past, I thought this would work but if I print it, it Seems like its not being read. I am still fairly new to MySQL so any help would be Great.
Non-numeric field value must be enclosed with single quote.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username ='" +strUsername + "'";
mySQLCommand.Connection=MySQLServer;
but you have to use Parameters to prevent SQL Injection.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username =#username";
mySQLCommand.Connection=MySQLServer;
mySQLCommand.Parameters.AddWithValue("#username",strUsername);
string con_string = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True";
string query = "SELECT * FROM Users WHERE UseName='" + txtUserName.Text.ToString() + "' AND Password='" + txtPassword.Text + "'";
SqlConnection Con = new SqlConnection(con_string);
SqlCommand Com = new SqlCommand(query, Con);
Con.Open();
SqlDataReader Reader;
Reader = Com.ExecuteReader();
if (Reader.Read())
{
lblStatus.Text="Successfully Login";
}
else
{
lblStatus.Text="UserName or Password error";
}
Con.Close();
As AVD said you should use parameters to prevent sql injection....

Categories