SQL代码出错时放入c#代码
本文关键字:代码 出错 SQL | 更新日期: 2023-09-27 17:49:35
我的一个朋友有一个问题,她在c#中做了一个项目,一切看起来都很好,但问题是,当她把SQL查询放在代码中时,她会得到错误,但是当我们在microsoft SQL Server中尝试代码时,它是有效的。
下面是显示错误的代码的三个示例:DataSet dsDelP = new DataSet();
string sql = "";
sql = "SELECT Grupi_ID, (p.emri + ' ' + p.mbiemri) as Profesori , k.EmriKlases as Klasa, d.emri as Dita, Ora_fillimit as Fillimi, Ora_mbarimit as Mbarimi";
sql += "FROM grupetOraret gro";
sql += "inner join Profesori p on gro.Profesori_ID=p.Profesor_ID";
sql += "inner join Klasa k on gro.Klasa_ID=k.Klasa_ID";
sql += "inner join Dita d on gro.ID_Dita=d.ID_dita";
SqlDataAdapter daDelP = new SqlDataAdapter(sql, con);
daDelP.Fill(dsDelP, "grupetOraret");
dataGridViewKerkoOrarin.DataSource = dsDelP.Tables[0].DefaultView;
没有空格。你应该在每一行(开头或结尾)加上它们。假设查询本身是正确的(只要您已经检查过),它应该是这样的:
sql = "SELECT Grupi_ID, (p.emri + ' ' + p.mbiemri) as Profesori , k.EmriKlases as Klasa, d.emri as Dita, Ora_fillimit as Fillimi, Ora_mbarimit as Mbarimi ";
sql += "FROM grupetOraret gro ";
sql += "inner join Profesori p on gro.Profesori_ID=p.Profesor_ID ";
sql += "inner join Klasa k on gro.Klasa_ID=k.Klasa_ID ";
sql += "inner join Dita d on gro.ID_Dita=d.ID_dita ";
添加到sql变量后不会自动插入换行符,因此sql
最终看起来像
...FROM grupetOraret groinner join Profesori p on gro.Profesori_ID=p.Profesor_ID...
注意grupetOraret gro
和inner join
之间没有空格
尝试使用@
多行字符串文字,使事情更容易和更有效:
string sql = @"
SELECT Grupi_ID, (p.emri + ' ' + p.mbiemri) as Profesori , k.EmriKlases as Klasa, d.emri as Dita, Ora_fillimit as Fillimi, Ora_mbarimit as Mbarimi
FROM grupetOraret gro
inner join Profesori p on gro.Profesori_ID=p.Profesor_ID
inner join Klasa k on gro.Klasa_ID=k.Klasa_ID
inner join Dita d on gro.ID_Dita=d.ID_dita";
您的SQL在字符串连接后看起来像这样:
<>之前选择……as MbarimiFROM ....在gro.Profesori_ID = p。Profesor_IDinner …之前每行的最后一个单词和下一行的第一个单词之间需要一个空格:
string sql = "... as Mbarimi";
sql += " FROM ...";
sql += " inner join Profesori p on gro.Profesori_ID=p.Profesor_ID";
sql += " inner join Klasa k on gro.Klasa_ID=k.Klasa_ID";
sql += " inner join Dita d on gro.ID_Dita=d.ID_dita";