C# “MatricNO”附近的语法不正确
我的代码中有一个SqlException: “MatricNO”附近的语法不正确 代码如下:C# “MatricNO”附近的语法不正确,c#,sql,sql-server,C#,Sql,Sql Server,我的代码中有一个SqlException: “MatricNO”附近的语法不正确 代码如下: public static StudentDetail GetStudent(string MatricNO) { //Calling on the connection class and get connection method SqlConnection connection = ConnectionClass.GetConnection(); //Sql select sta
public static StudentDetail GetStudent(string MatricNO)
{
//Calling on the connection class and get connection method
SqlConnection connection = ConnectionClass.GetConnection();
//Sql select statement that reads from the database
string selectStatement = "SELECT MatricNO,Faculty,Department,Course,FirstName,MiddleName,LastName" +
"FROM StudentInfo" +
"WHERE MatricNO=@MatricNO";
SqlCommand selectCommand=new SqlCommand(selectStatement,connection);
selectCommand.Parameters.AddWithValue("@MatricNO", MatricNO);
try
{
connection.Open();
SqlDataReader reader = selectCommand.ExecuteReader(CommandBehavior.SingleRow);
if(reader.Read())
{
//Read the database information into the StudentDetail Class
StudentDetail studentDetail=new StudentDetail();
studentDetail.Studentmatricno = reader["MatricNO"].ToString();
studentDetail.Faculty = reader["Faculty"].ToString();
studentDetail.Dept = reader["Department"].ToString();
studentDetail.Course = reader["Course"].ToString();
studentDetail.Firstname = reader["FirstName"].ToString();
studentDetail.Middlename = reader["MiddleName"].ToString();
studentDetail.Surname = reader["LastName"].ToString();
return studentDetail; //return all that has been read to the student detail class
}
else
{
// return null if queried record does not exist
return null;
}
}
catch (SqlException ex)
{
throw ex;
}
finally
{
connection.Close();
}
}
有人能帮我解决这个问题吗?您的SQL查询在字段列表和表名后需要空格:
string selectStatement =
"SELECT MatricNO,Faculty,Department,Course,FirstName,MiddleName,LastName " +
"FROM StudentInfo " +
"WHERE MatricNO=@MatricNO";
您还可以使用逐字字符串文字:
string selectStatement =
@"SELECT MatricNO,Faculty,Department,Course,FirstName,MiddleName,LastName
FROM StudentInfo
WHERE MatricNO=@MatricNO";
在FROM和SELECT以及FROM和WHERE子句之间需要空格
最好查看从字符串连接生成的SQL,并直接在DB上尝试 selectStatement的价值是什么?感谢您的回复。这是我在stackoverflow上的第一个问题
string selectStatement = "SELECT MatricNO,Faculty,Department,Course,FirstName,MiddleName,LastName" +
" FROM StudentInfo" +
" WHERE MatricNO=@MatricNO";