C# &引用;ExecuteOnQuery:连接属性尚未初始化;
代码如下: 错误是: 连接属性尚未初始化C# &引用;ExecuteOnQuery:连接属性尚未初始化;,c#,ms-access-2007,C#,Ms Access 2007,代码如下: 错误是: 连接属性尚未初始化 Access DB连接中存在3个主要问题: 打开OLE DB连接时,OleDbConnection连接字符串属性尚未初始化(请注意,con与此上下文中的conn不同) 将连接字符串错误地分配给变量conn,该变量声明为OleDbCommand,请改用OleDbConnection 连接字符串数据源路径似乎无效,原因是使用斜杠符号作为目录分隔符(假设目标文件存在于Windows文件夹中),使用反斜杠转义序列(\\)或使用带有文字字符串的单反斜杠(例如,@“
Access DB连接中存在3个主要问题:
OleDbConnection
连接字符串属性尚未初始化(请注意,con
与此上下文中的conn
不同)conn
,该变量声明为OleDbCommand
,请改用OleDbConnection
\\
)或使用带有文字字符串的单反斜杠(例如,@“Provider=Microsoft.ACE.OLEDB.12.0;数据源=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连接而添加的
语句应在使用后立即释放资源
类似问题:
con和conn是否不同?是的,正如@PrashanthBenny指出的,您需要更改“con.Close”和“con.Open”以使用“conn”
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();
}