c#子查询不起作用

时间:2017-01-28 11:57:16

标签: c# mysql

我喜欢将子查询添加到mysql数据库,但它给了我错误。

string q = "INSERT INTO table1(isbn,date,ID,title) 
values('" + this.textBoxisbn.Text + "','" + this.dateTimePicker1.Value.ToString("yyyy-MM-dd") + "','" + this.textBoxk.Text + "'(select title from books where isbn=" + textBox1.Text + "')'" + "');";

2 个答案:

答案 0 :(得分:0)

你错过了一个逗号。在子查询之前添加+","+

string q = "INSERT INTO table1(isbn,date,ID,title) 
values('" + this.textBoxisbn.Text + "','" + 
this.dateTimePicker1.Value.ToString("yyyy-MM-dd") + "','" + 
this.textBoxk.Text + "','" + "'(select title from books 
where isbn=" + textBox1.Text + "')'" + "');";

提示:最好在查询中使用占位符以及预处理语句而不是执行此操作('" + this.textBoxisbn.Text + "','"...

答案 1 :(得分:0)

逐字字符串字符串插值的帮助下,使查询可读

   string q = 
     $@"INSERT INTO table1(
          Isbn,
          Date,
          ID,
          Title) 
        VALUES(
          '{textBoxisbn.Text}',
          '{dateTimePicker1.Value.ToString("yyyy-MM-dd")}',
          '{textBoxk.Text}',
          (SELECT Title
             FROM Books
            WHERE Isbn = '{textBox1.Text}'))";

您可以轻松找到查询中的所有语法错误。进一步改进是将查询更改为参数化一:

   string q = 
     $@"INSERT INTO table1(
          Isbn,
          Date,
          ID,
          Title) 
        VALUES(
          @prm_Isbn,
          @prm_Date,
          @prm_Id,
          (SELECT Title
             FROM Books
            WHERE Isbn = @prm_IsbnForTitle))";