InvalidOperationException unhandeled。它在运行时不显示任何错误,但在执行命令时显示此错误

时间:2013-09-16 09:09:15

标签: c# visual-studio ms-access

你可以在这里获得截图“http://i.imgur.com/9K5WPVw.png

namespace session
{
    public class Broker
    {
        OleDbConnection connection;
        OleDbCommand command;

        private void connectto()
        {
            connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Tech Geek\Documents\Visual Studio 2012\WindowsFormsApplication8\Database.accdb;Persist Security Info=False");
            command = new OleDbCommand();
        }

        public Broker()
        {
            connectto();
        }

        public void Insert(person p)
        {
            try
            {
                command.CommandText = "INSERT INTO n_account(customerid, sponsorname, applicantname, fatherhusbandsname, nomineename, applicantdob, nomineedob, houseno, state, district, tehsil, post,city, pincode, contactno, idprooftype, addressprooftype, panno, ammount, months, maturitydate, maturityfund, lastpremiumpaid) VALUES('" + p.Customerid + "','" + p.Sponsorname + "','" + p.Applicantname + "','" + p.Fatherhusbandsname + "','" + p.Nomineename + "','" + p.Applicantdob + "','" + p.Nomineedob + "','" + p.Houseno + "','" + p.State + "','" + p.District + "','" + p.Tehsil + "','" + p.Post + "','" + p.City + "','" + p.Pincode + "','" + p.Contactno + "','" + p.Idprooftype + "','" + p.Addressprooftype + "','" + p.Panno + "','" + p.Ammount + "','" + p.Months + "','" + p.Maturitydate + "','" + p.Maturityfund + "','" + p.Lastpremiumpaid + "')";
                command.CommandType = CommandType.Text;
                connection.Open();

                command.ExecuteNonQuery();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }
        }
    }
}

enter image description here

请帮忙

我还附上了错误的屏幕截图。我在另一个程序中使用了相同的代码 - 工作正常。我不知道这个发生了什么。

2 个答案:

答案 0 :(得分:3)

由于错误表明您尚未为该命令设置连接属性。

在此行之前

connection.Open();

添加

command.Connection = connection;

答案 1 :(得分:0)

似乎OleDbCommand Command属性未初始化。

确保设置命令属性或使用适当的构造函数,例如

conn.Open(); cmd = new OleDbCommand(sqlQuery, conn);