简体   繁体   中英

Syntax error near Source when trying to access a database C# asp.net

string databaseLocation = "|DataDirectory|\\Users.mdf";
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + databaseLocation + ";Integrated Security=True;User Instance=True";    
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandText = String.Format("SELECT * FROM Users WHERE Username = {0}", username);
command.CommandType = CommandType.Text;
command.Connection = sqlConnection;
sqlConnection.Open();
int numberOfRows = command.ExecuteNonQuery();
sqlConnection.Close();
return numberOfRows;

This should check the Users.mdf database for the number of occorances of the username. but im getting a "syntax error near Source" runtime error when it hits the ExecuteNonQuery. I cant find anything wrong... Please help :)

Your formatted sql statement is not including delimiters for the username:

command.CommandText = String.Format("SELECT * FROM Users WHERE Username = {0}", username);

sets the command text to something like:

SELECT * FROM Users WHERE Username = foo

This is easily corrected, but it would be better to use a SqlParameter :

command.CommandText = "SELECT * FROM Users WHERE Username = @username");
command.Parameters.AddWithValue("@username", username);

Also, ExecuteNonQuery will return -1 for the number of rows affected, since the select doesn't affect rows. Instead do:

command.CommandText = "SELECT COUNT(*) FROM Users WHERE Username = @username");
command.Parameters.AddWithValue("@username", username);
...
int numberOfRows = (int)command.ExecuteScalar();

Your code should be:

string databaseLocation = "|DataDirectory|\\Users.mdf";
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + databaseLocation + ";Integrated Security=True;User Instance=True";    
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT COUNT(*) FROM Users WHERE Username = @User";
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@User",username);
command.Connection = sqlConnection;
sqlConnection.Open();
int numberOfRows = command.ExecuteScalar();
sqlConnection.Close();
return numberOfRows;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM