您当前的查询很容易受到 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();
}
}
}