问题
Created a website login system but when I run it it keeps coming up with this error to the particular bit of coding below. Can someone PLEASE help me with this Error message on this particular code:
System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'user'.
Code:
public static User LoginUser(string login, string password)
{
//Check if user exists
string query = string.Format("SELECT COUNT(*) FROM TeesDB.dbo.user WHERE name = '{0}'",
login);
command.CommandText = query;
try
{
conn.Open();
int amountOfUsers = (int) command.ExecuteScalar();
if(amountOfUsers == 1)
{
//User exists, check if the password match
query = string.Format("SELECT password FROM users WHERE name = '{0}", login);
command.CommandText = query;
string dbPassword = command.ExecuteScalar().ToString();
if (dbPassword == password)
{
//password match. Login and password data are known to us.
//retrieve further user data from the database
query = string.Format("SELECT email, user_type FROM users WHERE name =
'{0}'", login);
command.CommandText = query;
SqlDataReader reader = command.ExecuteReader();
User user = null;
while (reader.Read())
{
string email = reader.GetString(0);
string type = reader.GetString(1);
user = new User(login, password, email, type);
}
return user;
}
else
{
//passwords do not match
return null;
}
}
else
{
//user exists
return null;
}
}
finally
{
conn.Close();
}
}
}
}
回答1:
That happens because USER is a reserved keyword. To refer to it in your queries you need to encapsulate the word between square brackets
string query = string.Format("SELECT COUNT(*) FROM [user] WHERE name = .....
but at this point, why in subsequent queries you use the name users? It is just a typo in the first query or in the next?
However, you should also keep in mind that string formatting your queries in that way is very bad.
You are at risk of Sql Injections and, if a single quote appears in your text values, the whole query will resul in an invalid syntax
As an example of a parameterized query to replace your query
string query = "SELECT COUNT(*) FROM [user] WHERE name = @name",
command.CommandText = query;
command.Parameters.AddWithValue("@name",login);
int amountOfUsers = (Convert.ToInt32(command.ExecuteScalar());
if(amountOfUsers > 0)
{
.....
}
Then the next problem is the password retrieved from the database and compared with the user input. Having this kind of code means the password is stored in clear text inside the database. A clear security risk. You should store passwords in an encrypted form. When you need to check the user credentials you apply the same crypting algorithm to the user input and checks against the password in the database.
You could do this in a single operation
string cryptPwd = EncryptPassword(password);
string query = "SELECT COUNT(*) FROM [user] WHERE name = @name and password = @cryptpwd",
....
来源:https://stackoverflow.com/questions/22735869/syntax-error-with-database-login-system