【问题标题】:"ExecuteNonQuery: Connection property has not been initialized."“ExecuteNonQuery:连接属性尚未初始化。”
【发布时间】:2017-03-02 19:50:33
【问题描述】:

代码如下:

 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();

错误是:

连接属性尚未初始化

【问题讨论】:

  • conconn 不同吗?
  • 是的,正如@PrashanthBenny 指出的那样,您需要更改 'con.Close' 和 'con.Open' 以使用 'Conn'

标签: c# ms-access-2007


【解决方案1】:

您的 Access DB 连接存在 3 个主要问题:

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

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

  3. 使用斜杠符号作为目录分隔符(假设目标文件存在于 Windows 文件夹中),连接字符串数据源路径似乎无效,使用反斜杠转义序列 (\\) 或使用文字字符串的单个反斜杠代替(例如 @ 987654331@)。

因此,正确的连接顺序应该是这样的:

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

【讨论】:

    猜你喜欢
    • 2012-05-03
    • 2011-07-22
    • 2012-08-20
    • 1970-01-01
    • 2013-03-28
    相关资源
    最近更新 更多