2015-12-21 38 views
0

我创建了一个连接到本地数据库的wpf应用程序,它有2个表,现在我遇到了一个错误,但我不确定代码中出了什么问题。谁能帮忙?C#WPF mysql字符串

我得到这个错误:

An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll

Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'left join author on book.author_id=author.id' at line 1

private void Filter_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     connection.Open(); 
     MySqlCommand cmd = connection.CreateCommand(); 

     cmd.CommandText = "SELECT * FROM book where book.name like ('" + Filter.Text + "%') left join author on book.author_id=author.id"; 

     cmd.ExecuteNonQuery(); 
     DataTable dt = new DataTable(); 
     MySqlDataAdapter da = new MySqlDataAdapter(cmd); 
     da.Fill(dt); 
     _dataView = new System.Data.DataView(dt); 
     _dataView.Sort = "name ASC,id ASC"; 
     BooksGrid.DataContext = dt; 
     connection.Close(); 
    } 
+1

什么错误给你的数据库管理器查询?看起来它不是一个有效的SQL。你有没有尝试过没有'('和')'?你不需要'ExecuteNonQuery'行。不要忘记使用'using'语句自动处理连接,命令和适配器,而不是手动调用'Close'方法。 –

+1

尝试翻转'join'和'where'子句部分。它可能没有什么区别,但它可能会期望你的连接发生在你的位置之前。 –

回答

1

末查询更改为

cmd.CommandText = "SELECT * FROM book left join author on book.author_id=author.id where book.name like ('" + Filter.Text + "%') and book.author_id=author.id"; 

附加的 “book.author_id = author.id” 子句以确保您只获取与author_id匹配的记录。

而不是cmd.ExecuteNonQuery(),您应该尝试并使用cmd.ExecuteReader(),因为您正在检索行。