2015-12-21 41 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(),因爲您正在檢索行。