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:
sets the command text to something like:
This is easily corrected, but it would be better to use a
SqlParameter:Also,
ExecuteNonQuerywill return -1 for the number of rows affected, since theselectdoesn’t affect rows. Instead do: