我想从我创建的表单中将记录添加到MS访问数据库中,并将该记录显示到datagridview ..用于插入记录我有以下代码,
{
OleDbConnection con = new OleDbConnection();
string constring = @"Provider = microsoft.jet.oledb.4.0;" + @"data source = c:\\Users\\logicwaves\\My Documents\\tbl_company.mdb";
con.ConnectionString = constring;
con.Open();
StringBuilder stb = new StringBuilder();
stb.Append("Insert into tbl_company(cmny_name, cmny_location,cmny_phn ) ");
stb.Append("Values('@cmny_name','@cmny_location','@cmny_phn')");
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = stb.ToString();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
但是在“cmd.ExecuteNonQuery();”它给出了“处理OleDbException”的错误......任何人都可以告诉我应该如何克服这个问题?
答案 0 :(得分:1)
我认为你需要这样的东西:
{
OleDbConnection con = new OleDbConnection();
string constring = @"Provider = microsoft.jet.oledb.4.0;" + @"data source = c:\\Users\\logicwaves\\My Documents\\tbl_company.mdb";
con.ConnectionString = constring;
con.Open();
StringBuilder stb = new StringBuilder();
stb.Append("Insert into tbl_company(cmny_name, cmny_location,cmny_phn ) ");
stb.Append("Values('@cmny_name','@cmny_location','@cmny_phn')");
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = stb.ToString();
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@cmny_name", OleDbType.Char, 10) = txtCompanyName.Text;
cmd.Parameters.Add("@cmny_location", OleDbType.Char, 30) = txtLocation.Text;
cmd.Parameters.Add("@cmny_phn", OleDbType.Char, 10) = txtPhoneNumber.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
您需要使用cmd.Parameters.Add()
方法将参数实际传递到查询中。当然,在我的例子中,我假设你有一些文本框控件,但这些输入可能来自任何地方。你明白了。