2017-03-02 265 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