我正在尝试获取下面的查询结果并将其显示在listBox中,但我一直收到此错误:
' a'附近的语法错误。
这是我的代码:
SqlConnection con = new SqlConnection(@"Data Source=JOHZZ\SQLEXPRESS;Initial Catalog=parking;Persist Security Info=True;User ID=SA;Password=Roses2004");
SqlCommand c3 = new SqlCommand("SELECT targa" +
"FROM mjete AS m " +
"INNER JOIN abonimi_mjet AS a" +
"ON m.mjeti_id = a.mjeti_id" +
"WHERE a.statusi = 'PASIV'" +
"AND m.klient_id = @idK", con);
con.Open();
c3.Parameters.AddWithValue("@idK",idK);
SqlDataReader reader2 = c3.ExecuteReader();
while (reader2.Read())
{
listBoxTarga.Items.Add(reader2.GetString(0));
}
reader2.Close();
con.Close();
我在SQL Server Management Studio中尝试了相同的查询,但它运行正常。
提前感谢您的帮助。
答案 0 :(得分:2)
你的线之间需要一个空格。使用+符号将它们一起添加为一个字符串,只需在每个字符串的末尾添加一个空格。
SqlCommand c3 = new SqlCommand("SELECT targa " +
"FROM mjete AS m INNER JOIN abonimi_mjet AS a " +
"ON m.mjeti_id = a.mjeti_id " +
"WHERE a.statusi = 'PASIV' " +
"AND m.klient_id = @idK", con);
由于c#文件中的换行符不是字符串换行符,所以现在你得到的是这个字符串。
"SELECT targaFROM mjete AS m INNER JOIN abonimi_mjet AS aON m.mjeti_id = a.mjeti_idWHERE a.statusi = 'PASIV'AND m.klient_id = @idK"
您应该将SqlConnection
实例封装在using
块中,以确保在使用它时始终关闭/处置它(即使在出现异常时)。您的SqlDataReader
实例也是如此。