2012-09-26 40 views
1

我想要的:我想把作者ID,但我只有作者的名字。来自表格作者。那么我怎么能得到作者身份证,在这个查询下面?奇怪的查询。从其他表中获取ID

INSERT INTO book (title, isbn, author_id) VALUES('" + BookTitle.Text.ToString() + "', '" + BookIsbn.Text.ToString() + "', '(SELECT id FROM author WHERE first_name = '" + BookAuthor.Text.ToString() + "')')"; 

错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Marijn')')' at line 1 

我希望我清楚我想要什么。

谢谢!

+4

尝试运行LOINQPAD该查询查询

( " INSERT INTO book (title, isbn, authorID) SELECT '" + BookTitle.Text.ToString() + "' as title, '" + BookIsbn.Text.ToString() + "' AS isbn, id as authorID FROM author WHERE first_name = '" + BookAuthor.Text.ToString() + "' " ) 

使用INSERT INTO...SELECT,看看你和**摆脱了明确的字符串值是什么(在生产代码中),请始终在查询中使用参数而不是字符串**。 – Tigran

+1

请请使用查询参数! – Bas

+0

我想你试图在这里执行一些动态查询。你能发布完整的代码行吗?这将有助于我们更准确地理解语法错误。 –

回答

1
Here you have to have function fn_getID(fname) which will return id. 

"INSERT INTO book (title, isbn, author_id) 
VALUES('" + BookTitle.Text.ToString() + "', '" + BookIsbn.Text.ToString() + "'"+fn_getID(BookAuthor.Text.ToString())) 
+0

谢谢!有用! – mithe

2

你不应该把第二个SELECT语句放在单引号中(MySQL把它解释为一个字符串)。

"INSERT INTO book (title, isbn, author_id) 
VALUES ('" + BookTitle.Text.ToString() + "', '" + BookIsbn.Text.ToString() + "', 
    (SELECT id FROM author WHERE first_name = '" + BookAuthor.Text.ToString() + "'))" 

PS请注意,将数据插入数据库的方法使其非常容易受到注入攻击。

+0

是的,我知道,这是一个学校项目。老师走了,我们没有得到任何代码或什么。 – mithe

0

您当前的查询为很可能容易受到sql注入的影响。最好的方法是使用参数化查询,使用SQLCommand and its parameters。我认为这是更好地利用ADO.Net

string query = "INSERT INTO book (title, isbn, authorID) 
       SELECT @title as title, 
         @isbn AS isbn, 
         id as authorID 
       FROM author 
       WHERE first_name = @author"; 

using (MySqlConnection conn = new MySqlConnection("connectionstringHere")) 
{ 
    using (MySqlCommand comm = new MySqlCommand()) 
    { 
     comm.Connection = conn; 
     comm.CommandType = CommandType.Text; 
     comm.CommandText = query; 
     comm.Parameters.AddWithValue("@title", BookTitle.Text.ToString()); 
     comm.Parameters.AddWithValue("@isbn", BookIsbn.Text.ToString()); 
     comm.Parameters.AddWithValue("@author", BookAuthor.Text.ToString()); 
     try 
     { 
      conn.Open(); 
      comm.ExecuteNonQuery; 
     } 
     catch (MySqlException ex) 
     { 
      // error here 
     } 
     finally 
     { 
      conn.Close(); 
     } 
    } 
}