-6

我的SqlException代码中有一个:

'MatricNO' 附近的语法不正确

这是代码:

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();
   }
}

谁能帮我解决这个问题?

4

2 回答 2

2

FROM你需要在andSELECTFROMandWHERE子句之间有空格

   string selectStatement = "SELECT MatricNO,Faculty,Department,Course,FirstName,MiddleName,LastName" +
                            " FROM StudentInfo" +
                            " WHERE MatricNO=@MatricNO";

从字符串连接中查看生成的 SQL 并直接在 DB 上尝试总是更好。

于 2013-10-09T15:00:38.843 回答
1

您的 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";
于 2013-10-09T15:00:23.457 回答