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

3 回答 3

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 请注意,您将数据插入数据库的方法使其非常容易受到注入攻击。

于 2012-09-26T07:51:37.707 回答
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()))
于 2012-09-26T07:48:48.203 回答
0

您当前的查询容易受到 sql 注入的影响。最好的方法是通过使用参数化查询SQLCommand and its parameters。而且我认为最好INSERT INTO...SELECT在您的查询中使用

(
"
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() + "'
"
)

使用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();
        }
    }
}
于 2012-09-26T07:57:38.790 回答