“ExecuteNonQuery:Connection属性尚未初始化。”

时间:2017-03-02 19:50:33

标签: c# ms-access-2007

以下是代码:

S3_KEY=akfladjlasdladldad

,错误是:

  

连接属性尚未初始化

1 个答案:

答案 0 :(得分:0)

Access数据库连接中存在3个主要问题:

    打开OLE DB连接时,
  1. OleDbConnection连接字符串属性未初始化(请注意con在此上下文中与conn不同)。

  2. 错误地将变量conn分配给OleDbCommand的连接字符串,改为使用OleDbConnection

  3. 通过对目录分隔符使用斜杠符号(假设目标文件存在于Windows文件夹中),连接字符串数据源路径似乎无效,使用反斜杠转义序列(\\)或使用文字字符串代替单反斜杠(例如@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\......")。

  4. 因此,正确的连接顺序应如下所示:

    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