C#访问数据库问题

时间:2015-08-19 17:38:39

标签: c# database database-connection

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = CommandType.Text;       
        System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection();
        con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\dhelm.ALLMATINC.001\Desktop\Db11.accdb";
        cmd.CommandText = @"insert into Table1 (Customer,Description,Color,Status,)VALUES('" + tBox3.Text + "','" + tBox1.Text + "','" + tBox12.Text + "','" + cBox2.Text + "')";
        cmd.Connection = con;
        con.Open();
        cmd.ExecuteNonQuery();
        System.Windows.Forms.MessageBox.Show("Recrod Succefully Created");
        con.Close();
    }
    catch(Exception ex)
    { MessageBox.Show("error " + ex); }


}

现在我的数据库已经存在 其他字段的主键是ID,它有像sqft rons peices等等。我不需要填写他们所有吗?我每次都会收到错误 INSERT INTO语句中的语法错误 [![在此处输入图像说明] [1]] [1]

3 个答案:

答案 0 :(得分:0)

好像你的SQL拼写错误了。正确的例子:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = CommandType.Text;       
        System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection();
        con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\dhelm.ALLMATINC.001\Desktop\Db11.accdb";
        cmd.CommandText = @"insert into Table1 (Customer,Description,Color,Status) VALUES('" + tBox3.Text + "','" + tBox1.Text + "','" + tBox12.Text + "','" + cBox2.Text + "')";
        cmd.Connection = con;
        con.Open();
        cmd.ExecuteNonQuery();
        System.Windows.Forms.MessageBox.Show("Recrod Succefully Created");
        con.Close();
    }
    catch(Exception ex)
    { 
        MessageBox.Show("error " + ex); 
    }
}

答案 1 :(得分:0)

您无需提供INSERT语句中所有列的值。 如果字段设置为自动增量或允许NULL值,则可以省略这些字段。 在您的情况下,我认为您应该将主键ID设置为自动增量,其他字段允许NULL值。

答案 2 :(得分:0)

你有额外的','在"状态" -field之后。您不应该将值直接附加到命令,而是使用参数化值。您也可以使用"使用" -statements自动关闭并处理连接和命令。这里有一些小代码可以帮助您:

using (var con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\dhelm.ALLMATINC.001\Desktop\Db11.accdb"))
{
    using (var cmd = new OleDbCommand(@"
        INSERT INTO 
            Table1(Customer,Description,Color,Status)
            VALUES(@Customer,@Description,@Color,@Status)
    ", con))
    {
        cmd.Parameters.Add(new OleDbParameter("@Customer", OleDbType.VarChar)).Value = tBox3.Text;
        cmd.Parameters.Add(new OleDbParameter("@Description", OleDbType.VarChar)).Value = tBox1.Text;
        cmd.Parameters.Add(new OleDbParameter("@Color", OleDbType.VarChar)).Value = tBox12.Text;
        cmd.Parameters.Add(new OleDbParameter("@Status", OleDbType.VarChar)).Value = cBox2.Text;

        con.Open();

        cmd.ExecuteNonQuery();

        System.Windows.Forms.MessageBox.Show("Recrod Succefully Created");
    }
}