我得到一个我不理解的异常:
System.Data.SqlClient.SqlException:“ Clienti”附近的语法不正确。”
这是导致错误的代码:
string connectionString = @"Data Source=VONWOLFENSPC\MSSQLSERVER01;Initial Catalog=Gestionare_excursii_agentie_turism;Integrated Security=True";
SqlConnection sqlCon = new SqlConnection(connectionString: connectionString);
string selectsql = "Select G.Nume, G.Prenume, G.Telefon, G.NumarInsotitori, " +
"G.ClientID, G.Sex, " +
"(Select E.Nume From Excursii E where E.ExcursieID LIKE G.ExcursieID) AS Excursie" +
"From Clienti G Where G.CNP Like @cnp";
SqlCommand cmd = new SqlCommand(selectsql, sqlCon);
cmd.Parameters.AddWithValue("@cnp", comboBox2.Text);
try
{
sqlCon.Open();
// error happens on the next line
using (SqlDataReader read = cmd.ExecuteReader())
{
while(read.Read())
{
//...
}
}
}
finally
{
sqlCon.Close();
}
我该如何解决?
答案 0 :(得分:2)
使用多行字符串文字代替串联查询:
string selectsql = @"
Select G.Nume, G.Prenume, G.Telefon, G.NumarInsotitori, G.ClientID, G.Sex,
(
Select E.Nume
From Excursii E
where E.ExcursieID LIKE G.ExcursieID
) AS Excursie
From Clienti G
Where G.CNP Like @cnp
";
您可以直接将其粘贴到SSMS查询窗口中或从中粘贴以进行测试。
答案 1 :(得分:0)
您遇到的问题只是空格,如果您尝试重新检查字符串,则会在FROM之前注意到缺少空格。
此外,您需要使用using
string selectsql = @"SELECT
G.Nume
, G.Prenume
, G.Telefon
, G.NumarInsotitori
, G.ClientID
, G.Sex
, (SELECT E.Nume FROM Excursii E WHERE E.ExcursieID LIKE G.ExcursieID) AS Excursie
FROM
Clienti G
WHERE
G.CNP LIKE @cnp";
using(SqlConnection sqlCon = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(selectsql, sqlCon) )
using(SqlDataReader read = cmd.ExecuteReader())
{
cmd.Parameters.AddWithValue("@cnp", comboBox2.Text);
sqlCon.Open();
while(read.Read())
{
textBox1.Text = (read["Nume"].ToString());
textBox2.Text = (read["Prenume"].ToString());
textBox3.Text = (read["Telefon"].ToString());
textBox4.Text = (read["NumarInsotitori"].ToString());
textBox5.Text = (read["ClientID"].ToString());
comboBox1.Text = (read["Excursie"].ToString());
string sex = (read["Sex"].ToString());
if (sex == "M")
{
checkBox1.Checked = true;
checkBox2.Checked = false;
}
else
{
checkBox2.Checked = true;
checkBox1.Checked = false;
}
}
}