简体   繁体   English

尝试访问数据库C#asp.net时“源”附近的语法错误

[英]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. 这应该检查Users.mdf数据库中用户名的出现次数。 but im getting a "syntax error near Source" runtime error when it hits the ExecuteNonQuery. 但是当我击中ExecuteNonQuery时,我收到“源附近的语法错误”运行时错误。 I cant find anything wrong... Please help :) 我找不到任何错误...请帮助:)

Your formatted sql statement is not including delimiters for the username: 您格式化的sql语句不包含用户名的分隔符:

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 : 这很容易纠正,但是最好使用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. 另外,由于select不影响行,因此ExecuteNonQuery将为受影响的行数返回-1。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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