2012-09-26 61 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(); 
     } 
    } 
}