如何连接数据库和插入数据

时间:2013-02-21 01:21:20

标签: c#

我收到有关ExecuteNonquery is not initialized的错误。

我认为可能连接到数据库时出错,因为在执行系统之前MessageBox没有出现。

//Server Connection
private void ServerConnect()
{

    string ConnString;
    ConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=PLAN.accdb";
    TConn = new OleDbConnection(ConnString);
    TConn.Open();
    MessageBox.Show("You Are Connected.");
}

//ADD MEMOS
private void GetMemoList()
{

    string query;
    DataSet ds = new DataSet();
    query = "SELECT MEMOS_ID,DATE,TIME,MEMOS FROM TBLMEMOS ORDER BY DATE ASC";
    OleDbDataAdapter da = new OleDbDataAdapter(query, TConn);
    da.Fill(ds);
    this.dgv1.DataSource = ds.Tables[0];
}

private void AddMemo(string MemoDate, string MemoTime, string Memos)
{

    string acc;
    acc = "INSERT INTO TBLMEMOS (DATE,TIME,MEMOS) VALUES ('" + MemoDate + "','" + MemoTime + "','" + Memos + "')";
    OleDbCommand cmd = new OleDbCommand(); 
    cmd.CommandText = acc;
    cmd.Connection = TConn;
    cmd.ExecuteNonQuery();
}

private void btnAddMemos_Click(object sender, EventArgs e)
{

    AddMemo(this.dtpDate.Value.ToShortDateString(), this.dtpTime.Value.ToShortTimeString(), this.txtInfo.Text.Trim());
    GetMemoList();
    txtInfo.Clear();
}

1 个答案:

答案 0 :(得分:1)

尝试添加这样的参数。

cmd.Parameters.Add("p1", OleDbType.Char).Value = MemoDate ;