2017-03-02 269 views
0

下面是代碼:「ExecuteNonQuery:連接屬性尚未初始化。」

string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/charlyn_dale/Documents/Visual Studio 2010/Projects/LMS/WindowsFormsApplication2/Accounts.accdb;Persist Security Info=False"); 
      OleDbCommand conn = new OleDbCommand(str); 
      con.Open(); 
      string query = "insert into Account ([Username],[Password],FirstName,MiddleName,LastName,Age,Section,Gender,Address,AccountStatus) values('" + txt1.Text + "','" + txt2.Text + "','" + txt4.Text + "','" + txt5.Text + "','" + txt6.Text + "','" + txt7.Text + "','" + txt8.Text + "','" + cmb2.Text + "','" + txt9.Text + "','" + cmb1.Text + "')"; 
      OleDbCommand cmd = new OleDbCommand(query, con); 
      conn.ExecuteNonQuery(); 
      MessageBox.Show("Registration Success!"); 
      con.Close(); 

和錯誤是:

連接屬性尚未初始化

+0

是'con'和'conn'不同? –

+0

是的,正如@PrashanthBenny指出的,你需要改變'con.Close'和'con.Open'來使用'Conn' –

回答

0

有你的Access數據庫3個主要問題連接:

  1. OleDbConnection連接字符串屬性在打開OLE DB連接時未初始化(請注意,con與此上下文中的conn不同)。

  2. 錯誤地分配給變量conn的連接字符串聲明爲OleDbCommand,請改爲使用OleDbConnection

  3. 連接字符串數據源路徑似乎通過使用斜線符號爲目錄分隔符(假定目標文件存在Windows文件夾中),可使用反斜槓轉義序列(\\)或用文字串單反斜線代替(例如@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\......")無效。

因此,正確的連接順序應該是這樣的:

string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\charlyn_dale\\Documents\\Visual Studio 2010\\Projects\\LMS\\WindowsFormsApplication2\\Accounts.accdb;Persist Security Info=False"); 

using (OleDbConnection conn = new OleDbConnection(str)) 
{ 
    conn.Open(); 

    // security tips: better use parameter names to prevent SQL injection on queries 
    // and put value checking method for all textbox values (sanitize input) 
    string query = "insert into Account ([Username],[Password],FirstName,MiddleName,LastName,Age,Section,Gender,Address,AccountStatus) values ('" + txt1.Text + "','" + txt2.Text + "','" + txt4.Text + "','" + txt5.Text + "','" + txt6.Text + "','" + txt7.Text + "','" + txt8.Text + "','" + cmb2.Text + "','" + txt9.Text + "','" + cmb1.Text + "')"; 
    using (OleDbCommand cmd = new OleDbCommand(query, conn)) 
    { 
     conn.ExecuteNonQuery(); 
    } 
    ... // other stuff 
    conn.Close(); 
} 

注:由於添加到OLE DB連接using報表應立即使用,以騰出資源後丟棄。

類似的問題:

get an error as ExecuteNonQuery:Connection property has not been initialized

ExecuteNonQuery: Connection property has not been initialized (access database)

ExecuteNonQuery: Connection property has not been initialized