C# Syntax Error Near Table Name [duplicate] - c#

This question already has answers here:
Simple SELECT statement fails with "syntax to use near", "ORA-00906", "syntax error at or near" or "syntax near the keyword"
(2 answers)
Creating table names that are reserved words/keywords in MS SQL Server [closed]
(11 answers)
Closed 8 years ago.
I am having some problem when trying to check login credential for 3-tier project in C#.
Currently, I have a table named User with userName and password columns.
In my BusinessLogicLayer, I get the user input and pass them to dataAccessLayer:
public string checkCredential(string userName, string password)
{
string returnMessage = "";
User user = new User(userName, password);
Boolean success = user.checkCredential();
if (!success)
{
returnMessage += "Username and password does not match!";
}
else
{
returnMessage = "";
}
return returnMessage;
}
In my Data Access Layer, I got a method to check for login creddential:
public Boolean checkCredential()
{
Boolean result = false;
using (var connection = new SqlConnection(FFTHDb.connectionString)) // get your connection string from the other class here
{
SqlCommand command = new SqlCommand("SELECT userName, password FROM User WHERE userName = '" + userName + "' AND password = '" + password + "'", connection);
connection.Open();
using (var dr = command.ExecuteReader())
{
if (dr.Read())
{
result = true;
}
}
}
return result;
}
And I got a separated class to set the connection string:
public static string connectionString = DataAccessLayer.Properties.Settings.Default.DBConnStr;
public static SqlDataReader executeReader(string query)
{
SqlDataReader result = null;
System.Diagnostics.Debug.WriteLine("FFTHDb executeReader: " + query);
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
result = command.ExecuteReader();
connection.Close();
return result;
}
There is no compilation errors. And I double checked for the table name and columns in database. However, it just keeps telling me that there is syntax error near User. I wonder why is it so.
Thanks in advance.

User is a reserved keyword on T-SQL. You should use it with square brackets like [User]
Also using parameterized queries always a good practice.
And Never store passwords in plain text! Use SHA-512 hash.

User is a reserved keyword so you need to add square brackets around it. For a list see here.
So, you should do it like this
SELECT userName, password FROM [User] WHERE userName =

Problem : the table name which you have provided is User is a Keyword in Transact-SQL.
Reserved Words
Solution: Enclose the reserved word User in square brackets [].
Solution 1:
SqlCommand command = new SqlCommand("SELECT userName, password FROM [User] WHERE userName = '" + userName + "' AND password = '" + password + "'", connection);
Solution 2:
SqlCommand command = new SqlCommand("SELECT userName, password FROM [User] WHERE userName= #username AND password = #password", connection);
command.Parameters.AddWithValue("#username",userName);
command.Parameters.AddWithValue("#password",password);

Related

C# SQL UPDATE SYNTAX ERROR

I am having silly trouble with an UPDATE statement. I am trying to change password in a user table with UPDATE, and I keep getting "syntax error". Can't find the reason...
In my table, I have 6 different columns including username and password.
String salt = ""; // Initializing salt string variable to save the salt
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database_MT.accdb;Jet OLEDB:Database Password=********************");
con.Open(); //Opening the connection
OleDbCommand cmd1 = new OleDbCommand("UPDATE users SET password = #pass WHERE username = #user", con);
salt = CreateRandomSalt();
cmd1.Parameters.AddWithValue("#pass", hashPassword(newPasswordTextBox.Text, salt));
cmd1.Parameters.AddWithValue("#user", verifiedUser);
try
{
cmd1.ExecuteNonQuery();
this.DialogResult = DialogResult.OK;
}
catch (Exception ex)
{
string newException = ex.ToString();
ThreadExceptionForm newEx = new ThreadExceptionForm(newException);
newEx.ShowDialog();
}
The password columnname and/or the users table-name might be keywords, so you'll have to escape them.
In SQL Server you use brackets to do so:
UPDATE [users] SET [password] = #pass WHERE username = #user

Assistance checking values in a database vs values entered in a log in form in Visual Studio 2010 and using MS Access 2010

Below is the code that is executed when the user clicks the submit button. However, everytime I try it I get an error which reads "Syntax error in FROM clause"
What I'm trying to do is check the values entered in te login screen against the values stored in the database, but there seems to be an issue with my FROM clause that I am not picking up on. Any pointers are appreciated.
string userName = "";
string passWord = "";
userName = txtUserName.Text;
passWord = txtPassword.Text;
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\kazan_000\Desktop\Risk Manager\Risk Manager\Risk Manager Database 2.0.accdb";
string cmdText = "SELECT * from User where userName=? and passWord=?";
using (OleDbConnection con = new OleDbConnection(conString))
using (OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.AddWithValue("#p1", userName);
cmd.Parameters.AddWithValue("#p2", passWord);
int result = (int)cmd.ExecuteScalar();
if (result > 0)
MessageBox.Show("Login Successful");
else
MessageBox.Show("Invalid Credentials, Please Re-Enter");
}
Problem : user and password are reserved words in MS-Access .
Solution : you need to enclose the reserved words in square brackets []
Try This:
string cmdText = "SELECT * from [User] where userName=? and [passWord]=?";
Strange mixture you have there.
"Select * From [User] Where userName = #p1 and [password] = #p2" is what you are looking for.

.NET SqlDataReader: SqlException was unhandled by user code

Working on building a simple .NET web application using a SQL Server table created. I continuely get errors in regards to the SqlDataReader, and am stuck on where I'm going wrong.
Here is my error: Additional information: Incorrect syntax near the keyword 'Table'.
Here is my code:
EDIT:
bool authenticated = AuthenticateMe(txtUsername.Text, txtPassword.Text);
if (authenticated)
{
Response.Redirect("Home.aspx");
}
else
{
Response.Redirect("Default.aspx");
}
}
private bool AuthenticateMe(string username, string password)
{
// string ErrorMessage = "";
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30";
string commandText = "SELECT Username from [Table] where Username = #name AND Password = #pwd";
// try
// {
using (SqlConnection sqlConnection1 = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, sqlConnection1))
{
sqlConnection1.Open();
cmd.Parameters.AddWithValue("#name", username);
cmd.Parameters.AddWithValue("#pwd", password);
int result = (int)cmd.ExecuteNonQuery();
if (result > 0)
{
return true;
}
else
{
return false;
}
}
}
1st Version (prior to edit):
protected void bnLogin_Click(object sender, EventArgs e)
{
bool authenticated = AuthenticateMe(txtUsername.Text, txtPassword.Text);
if (authenticated)
{
Response.Redirect("Home.aspx");
}
else
{
Response.Redirect("Default.aspx");
}
}
private bool AuthenticateMe(string userName, string password)
{
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
sqlConnection1.Open();
SqlCommand cmd = new SqlCommand("SELECT Username from Table where Username = userName");
cmd.Connection = sqlConnection1;
SqlDataReader reader = cmd.ExecuteReader();
Response.Write("Entered Sucessfully");
reader = cmd.ExecuteReader();
string localUserName = (string)reader["Username"];
sqlConnection1.Close();
if (userName.Equals(localUserName))
{
return true;
}
else
{
return false;
}
Table is a reserved keyword in SQL. Try putting square brackets around it:
SqlCommand cmd = new SqlCommand("SELECT Username from [Table] where Username = userName");
Table is a keyword. If your table is called Table, your sql must escape it. Try [Table].
Note also that you'll want to use a parameter for the username - i.e. where Username = #userName, where you also add a parameter with that name to the command with the appropriate value.
Your AuthenticateMe method seems a bit wrong and ineffective to authenticate the user
You use a reserved keyword (Table) without the proper delimiters
(Square brackets)
You don't pass the username and the password to the query that checks
if the user is present
You call two times the ExecuteReader (?)
You check the returned value from the query with the same value used
for the search (useless)
So you could rewrite the code in this way
private bool AuthenticateMe(string userName, string password)
{
string connectionString = #".....";
string commandText = "SELECT COUNT(*) from [Table] where Username = #name AND Pass = #pwd");
using(SqlConnection sqlConnection1 = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(commandText, sqlConnection1))
{
sqlConnection1.Open();
cmd.Parameters.AddWithValue("#name", username);
cmd.Parameters.AddWithValue("#pwd", password);
int result = Convert.ToInt32(cmd.ExecuteScalar());
return (result > 0);
}
}
Also, keep in mind that is considered a bad practice to store the passwords in the database in plain text. Some kind of hash function should be applied to the password memorized to forbid any security problem if someone get a copy of the database.
I think there are 2 issues with your SQL query.
"SELECT Username from Table where Username = userName"
Table is a reserved keyword. Use another name for the table or [Table].
The last part, Username = username, is also wrong. If your intention was to have a constant string there, you should consider putting the username in quotes \'username\'. Don't forget about the escape symbol. And if you want to pass a parameter to the SQLCommand, use #username in the query and pass the value this way
cmd.Parameters["#username"].Value = "Bob";

Login from database

based on this tutorial: http://www.codeproject.com/Tips/423233/How-to-Connect-to-MySQL-Using-Csharp
I have a table
CREATE TABLE Employee {
ID int,
Name varchar(20),
Password varchar(20),
}
and now I have a new row
INSERT INTO employee(ID, Name, Password) VALUES (001, 'John', 'abc')
and here's how I try to receive the Password as a string from ID that is taken from TextBox
MySqlConnection connection = new MySqlConnection("Server=localhost; Database=sad - final project; Uid=root; Pwd=");
connection.Open();
try
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT Password FROM employee WHERE ID = '" + Input_ID + "'";
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataSet myDataSet = new DataSet();
adapter.Fill(myDataSet);
} catch blablabla
If Input_ID is 001, I expect to get a string from myDataSet that contains the password (which is "abc") so that I can compare it with password input from another textbox. How could I convert this myDataSet to String?
How about using ExecuteScalar instead:
var pwd = command.ExecuteScalar() as string;
and now you have the string. I'm not going to address the security concerns with your code in this answer, they are vast.
DataRow row = myDataSet.Tables[0].Row[0];
string password = row["Password"];
should get you the string.
You should use ExecuteScalar to get the password to string. Also you should use the using keyword to ensure proper disposal of your connection/command. Also, you need to use parameters in your select to prevent injection.
using (MySqlConnection connection = new MySqlConnection("Server=localhost; Database=sad - final project; Uid=root; Pwd=");
using (MySqlCommand command = new MySqlCommand("SELECT password FROM employee WHERE ID = #UserId", connection)
{
try
{
connection.Open();
command.Parameters.AddWithValue("#UserId", Input_ID);
var pwd = command.ExecuteScalar() as string;
//Do something with the stored password.
//Consider encryption and other security concerns when working with passwords.
}
catch (Exception ex)
{
//handle your exceptions
}
}

validating and changing a user's password

I have a simple C# windows form which acts as a login, but also has a form to change the password of a user.
When you click on Change Password the form loads with a text box of current password, new pass and confirm new pass, and one save button.
I have stored username in label so that current password can be checked if it is valid from database or not.
I am storing these in a table which I created in Microsoft SQL Server 2008.
The code is as follows so far.
SqlConnection connect = new SqlConnection(str);
connect.Open();
string username = label_username.Text;
string password = textBox_Current.Text;
string newPassword = textBox_New.Text;
string confirmPassword = textBox_Verify.Text;
string sqlquery = "UPDATE [Member] SET Password=#newpass where Username=#username";
SqlCommand cmd = new SqlCommand(sqlquery, connect);
cmd.Parameters.AddWithValue("#newpass", textBox_Verify.Text);
cmd.Parameters.AddWithValue("#username", label_username.Text);
cmd.Parameters.AddWithValue("#password", textBox_Current.Text);
cmd.Connection = connect;
cmd.ExecuteNonQuery();
sqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
if ((textBox_New.Text == reader["newPassword"].ToString()) & (textBox_Verify.Text == (reader["confirmPassword"].ToString()))) { }
}
MessageBox.Show("Password Changed Successfully!");
this.Close();
While executing above code, password change but I want to:
check validation like if the user had typed wrong password in current password.
newpassword and confirm password .
when user click on first save bottom blank password should not store in database, rather should give message 'please type the password'
How can this be done?
You really should not be storing these passwords in plain text. You should hash the password and store the hash. Then if you want to check if a password is correct hash the password the user typed and compare it to the hash stored for the user.
But, it sounds like you need help getting a value out of the database for the current user. Putting something like this in there, ought to do this for you. Please note that like I said above, this should really be retrieving a hash of the password, not the actual password in plain text.
string sqlquery = "SELECT Password FROM [Member] where Username=#username";
SqlCommand cmd = new SqlCommand(sqlquery, connect);
cmd.Parameters.AddWithValue("#username", label_username.Text);
cmd.Connection = connect;
string currentPassword = (string)cmd.ExecuteScalar();
if (currentPassword == textBox_Current.Text)
{
// PASSWORD IS CORRECT, CHANGE IT, NOW.
} else {
// WOW EASY BUDDY, NOT SO FAST
}
First you should use password hashing in your application, thus the password fields of the database should hold the hashed values.
Assuming this, to accomplish your goals,
consider your string username -> Hash it -> write a query to check whether that hashed value and the user's password's hash value stored in the database is the same
consider string password and string newPassword in your code -> Hash both -> check whether the hash values are the same
consider string password and string newPassword -> check whether each is null or the length is 0
Also you should perform these tasks in the following order:
1 -> 3 -> 2
Hope this helps...
protected void btn_PasswordChange(object sender, EventArgs e)
{
string constring = DataAccess.GetConnection();
SqlConnection con = new `SqlConnection`(constring);
{
if (con.State != ConnectionState.Open)
con.Open();
}
string str = "select * from tbl_MemberLogin where Password='" + txtoldpwd.Text + "'";
DataTable DT = new DataTable();
DT = objdut.GetDataTable(str);
if (DT.Rows.Count == 0)
{
lblmsg.Text = "Invalid current password";
lblmsg.ForeColor = System.Drawing.Color.Red;
}
else
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "update tbl_MemberLogin set Password='" + txtnewpwd.Text + "' where UserName='" + Session["UserName"].ToString() + "'";
cmd.ExecuteNonQuery();
lblmsg.Text = "Password changed successfully";
lblmsg.ForeColor = System.Drawing.Color.Green;
}
}

Categories

Resources