我想要的:我想把作者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
我希望我能说明我想要的东西。
谢谢!
答案 0 :(得分: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请注意,将数据插入数据库的方法使其非常容易受到注入攻击。
答案 1 :(得分: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()))
答案 2 :(得分: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();
}
}
}