【问题标题】:How to insert null values in Ms access using c#如何使用C#在Ms访问中插入空值
【发布时间】:2017-09-15 22:40:12
【问题描述】:

我只是像这样添加值 Mc access column data type (text,numeric-double,text,numeric-percentage) 但是我插入了这个值(john,"","","")这个值没有插入 这个错误 因为我只有名单 帮帮我

在 biodata.exe 中发生了“System.NullReferenceException”类型的第一次机会异常

附加信息:对象引用未设置为对象的实例。

private void button1_Click(object sender, EventArgs e)
{

      con.Open();
       cmd.CommandText = "insert into hhh (name,answerinfloat,subject,avg)VALUES('" + a.Text + "','" + b.Text + "','" + c.Text + "','" + d.Text + "')";

        cmd.CommandType = CommandType.Text;

        cmd.Parameters.AddWithValue("name", a.Text);
        cmd.Parameters.AddWithValue("answerinfloat", b.Text);

        cmd.Parameters.AddWithValue("subject", c.Text);
        cmd.Parameters.AddWithValue("avg", d.Text);



        int n = cmd.ExecuteNonQuery();


        if (n > 0)
        {
            MessageBox.Show("Record Submitted", "Congrats");
        }
        else
            MessageBox.Show("insertion failed");

   con.Close();

}

【问题讨论】:

  • 如果您在查询文本中省略列名,那么您需要为表中存在的所有列提供值。只需添加列的名称并查看什么是 Sql Injection hack。您的代码已准备好被黑客入侵。
  • 我强烈建议您关注Parameterizing your query
  • 警告:您的代码容易受到 sql 注入攻击。不要使用字符串连接。使用参数。

标签: c# ms-access-2010


【解决方案1】:

指定要插入的列:

cmd.CommandText = "insert into hhh (col1,col2,col3,col4) VALUES('" + a.Text + "','" + b.Text + "','" + c.Text + "','" + d.Text + "')";

只需将 col1、col2 等替换为您希望插入的列的实际名称。您省略的列不会得到值,并且会变为 NULL(前提是它们实际上允许 NULL)

正如其他人所评论的,您应该考虑使用参数化查询,而不是将值连接到 SQL 语句中。它会使您的代码容易受到注入攻击。

【讨论】:

  • 是的,我知道,但只是尝试如何插入空行或空行我单击按钮
【解决方案2】:

这很可能是因为您的主键为 @@IDENTITY 列,因此您需要明确指定所有列

insert into hhh(col1, col2, col3, ...) VALUES('" + 

您的代码再次容易受到SQL 注入的影响。使用参数化查询见Preventing SQL injection on insert

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    相关资源
    最近更新 更多