ExecuteNonQuery: Connection property has not been initialized (access database)

倾然丶 夕夏残阳落幕 提交于 2020-03-06 04:35:49

问题


what's wrong with my code?I just want to add data into access database but it show ExecuteNonQuery:

Connection property has not been initialized.

It's pretty weird because in other project code similar to this works just fine.

OleDbCommand command = new OleDbCommand();
OleDbConnection connect = new OleDbConnection();
OleDbDataReader reader;

    public Absen()
    {
        InitializeComponent();
    }

    MainForm form_utama;

    private void Absen_Load(object sender, EventArgs e)
    {
        connect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Visual Studio Project\Minor baru - back up\Minor baru\Absensi.accdb;Persist Security Info=False;";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (idkaryawantxt.Text != "")
        {
            string q = "insert into tableAbsensi (ID,ID_divisi,Waktu,Tanggal) values ('" + idkaryawantxt.Text.ToString() + "','" + iddivisitxt.Text.ToString() + "','" + (DateTime.Now.ToString("hh:mm :")) + "','" + (DateTime.Now.ToString("MM-dd-yyyy")) + "')";
            dosomething(q);
        }
    }

    private void dosomething(String q)
    {
        try
            {
                connect.Open();
                command.CommandText = q;
                command.ExecuteNonQuery();
                connect.Close();
            }
            catch (Exception e)
            {
                connect.Close();
                MessageBox.Show(e.Message.ToString());
            }
    }

回答1:


You didn't set your Command's Connection property

command.Connection = connect;

Before execute your command you should set it as the error said



来源:https://stackoverflow.com/questions/21294828/executenonquery-connection-property-has-not-been-initialized-access-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!