C# 奇怪的疑问。从另一个表中获取id
我想要的:我想输入作者id,但我只知道作者的名字。来自表格作者。那么,在下面的查询中,我如何获得作者idC# 奇怪的疑问。从另一个表中获取id,c#,mysql,C#,Mysql,我想要的:我想输入作者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()
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
我希望我清楚地表明我想要什么
谢谢大家! 不应该将第二条SELECT语句放在单引号中(MySQL将其解释为字符串)
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()))
PS注意,您将数据插入数据库的方法使其非常容易受到注入攻击。您当前的查询非常容易受到sql注入攻击。最好的方法是使用
SQLCommand及其参数来使用参数化查询。我认为最好在查询中使用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();
}
}
}
尝试在LOINQPAD中运行该查询,查看您获得了什么值并删除了清除字符串(在生产代码中),请始终在查询中使用参数而不是字符串。请使用查询参数!我猜您正在尝试执行一些动态查询。你能把生成这个动态查询的整个代码行发布到哪里吗?这将帮助我们更准确地理解语法错误。生成这样的sql查询可能会导致攻击,请改用参数。是的,我知道,这是一个学校项目。老师不在,我们得不到任何密码什么的。
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();
}
}
}