下面的查询适用于HeidiSQL,但在尝试在C#
中使用它时会出错SELECT title.id,title.title,title.production_year,movie_info.info FROM title NATURAL JOIN movie_info WHERE title.id <= 1000;
它告诉我以下内容:
我使用以下代码检索MySqlDataReader
对象:
public override MySqlDataReader Retrieve(string sql)
{
MySqlCommand cmd = new MySqlCommand(sql, GetConnection());
return cmd.ExecuteReader();
}
我从我的主要方法中调用它:
static void Main(string[] args)
{
MySQLFacade facade = new MySQLFacade("127.0.0.1", "omitted", "omitted", "imdb");
MySqlDataReader reader = facade.Retrieve(
"SELECT title.id,title.title,title.production_year,movie_info.info" +
"FROM title " +
"NATURAL JOIN movie_info" +
" WHERE title.id <= 1000;");
using (reader)
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine(reader.GetValue(i));
}
Console.WriteLine();
}
}
Console.ReadLine();
}
与数据库管理器相比,我是否可能遗漏了在C#中使用格式化SQL字符串的内容?
答案 0 :(得分:2)
FROM
之前缺少一个空格:
MySqlDataReader reader = facade.Retrieve(
"SELECT title.id,title.title,title.production_year,movie_info.info" + // <-- here
"FROM title " +
"NATURAL JOIN movie_info" +
" WHERE title.id <= 1000;");
在你的回答中,你已将所有内容放入一行,并添加了缺失的空格。
答案 1 :(得分:0)
使用@作为多行,最好使用参数来避免sql注入:
static void Main(string[] args)
{
MySQLFacade facade = new MySQLFacade("127.0.0.1", "omitted", "omitted", "imdb");
MySqlDataReader reader = facade.Retrieve(
@"SELECT title.id,title.title,title.production_year,movie_info.info
FROM title
NATURAL JOIN movie_info
WHERE title.id <= 1000");
using (reader)
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine(reader.GetValue(i));
}
Console.WriteLine();
}
}
Console.ReadLine();
}