2013-11-09 170 views
0

好吧,我創建了Visual Studio的C#(2012)和Access之間的連接。這意味着,我已經完成了手動方式(沒有代碼)。但是,這種方法無法幫助我完成我想要的功能,所以我也完成了編碼方式。我的連接有問題C# - Microsoft Access 2010

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Data.OleDb; 
using System.Configuration; 
using System.Xml.Serialization; 

namespace WindowsFormsApplication1 
{ 
public partial class horaireForm : Form 
{ 
    DateTime semSess; 
    int numSemaine; 

    int jourSem; 
    int periode; 
    string theoOuLabo; 

    string lesCours; 
    string cours; 

    string lesProfs; 
    string unprof; 

    string lesLocaux; 
    string lesGroupes; 
    string laComm; 

    string conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Stanley\\Desktop\\stuff\\Hiver 2013\\Horaires_EcranA2013.accdb"; 

(對不起,如果它很長)。無論如何,在此之後,我在這裏得到這個代碼,它從組合框中獲取信息(每個案例是大學學期的幾周的日期)。由於顯然我不能選擇主鍵,如果它是組合框中的值,我決定使用日期作爲組合框中選擇的值,然後使用它來選擇數據庫中的實際主鍵。

semSess = Convert.ToDateTime(comboSemSess.Text); 
     OleDbConnection laConn = new OleDbConnection(conn); 

     try 
     { 
      laConn.Open(); 

      laComm = "SELECT NumeroSemaine FROM SemainDelaSession WHERE DebutSemaine = " + semSess; 

      OleDbCommand myAccessCommand = new OleDbCommand(laComm, laConn); 

      OleDbDataReader reader = myAccessCommand.ExecuteReader(); 

      while (reader.Read()) 
      { 
       numSemaine = Convert.ToInt32(reader["NumeroSemaine"]); 
      } 
     } 

     catch 
     { 
      MessageBox.Show("Une erreur s'est produite en accédant à la base de données"); 
     } 

     finally 
     { 
      laConn.Close(); 
     } 

但是,我仍然無法連接。它仍然獲取MessageBox。這是否與我之前做過另一個連接,或者我鍵入connectionString的方式有關,因爲我不知道。

+0

你爲什麼不抓住例外,看看它有什麼說法? catch(Exception ex){MessageBox.Show(ex.ToString())}並且你將會知道什麼是錯誤的。 – lauCosma

+0

感謝您的回答。我完全忘了你可以這樣做。無論如何,我試圖做到這一點......當我嘗試將「semSess」分配給「DebutSemaine」時,它會出現語法錯誤。說像「DebutSemaine = 2013-02-25 00:00:00」。 –

回答

0

我可以在While (reader.Read())塊中看到幾個問題......每次覆蓋numSemaine,因此您只能在數據讀取器中獲得最後一個結果。 此外,SELECT語句中的日期應該包含引號(在SQL中將它視爲字符串),實際上它應該是參數化的而不是concantenated(很難SQL從組合框注入但不是不可能,無論如何它都是很好的實踐)。 此外,路徑只需要一個目錄之間的\,而不是兩個。

+0

感謝您的回覆。但是,每次我只用一個「\」放置路徑時,Visual Studio將其標記爲紅色。 –