【问题标题】:Can't connect with database c#无法连接数据库c#
【发布时间】:2017-07-19 22:39:32
【问题描述】:

cmd.executenonquery 显示(不能有空值)错误!

下面是代码

我正在尝试将数据插入文本框并发送到数据库中的表,但它一直显示为 NULL。

SqlConnection con = new SqlConnection("Data Source=*******;Initial Catalog=MaleFemale;Integrated Security=True");

public MainWindow()
{
    InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (con.State == System.Data.ConnectionState.Closed)
    {
        con.Open();

        SqlCommand cmd = new SqlCommand("insert into TableMaleFemale(Name,EiD,Gender) values ('" + NametextBox.Text + "', '" + EiDtextBox.Text + "', '" + GendertextBox.Text + "')", con);


        cmd.ExecuteNonQuery();
        cmd.Dispose();

        con.Close();
    }
}

【问题讨论】:

  • 对于初学者,您的代码对 SQL 注入是开放的。这很可能是问题的根源。发生错误时,cmd 正在执行的 exact 查询是什么(在您插入这些值之后)以及 exact 错误消息是什么?
  • 什么是SQL注入
  • en.wikipedia.org/wiki/SQL_injection 这基本上意味着您在盲目地执行用户写入应用程序的任何 SQL 代码。在 .NET 中查看称为“参数化查询”的东西。
  • 哦。好的。一定是SQL注入?
  • 检查 TableMaleFemale 的表定义是否有任何设置为“NOT NULL”的列。您可能没有在插入语句中提供足够的列。

标签: c#


【解决方案1】:

你应该用你的代码改变三件事:

  1. 不要创建一个连接对象并重复使用它 - 连接由 .NET 汇集,因此创建它们通常不是一个昂贵的过程,而且您不必再担心检查当前状态。李>
  2. 使用完连接和命令后立即处理它们 - 使用 using 语句块很方便
  3. 使用参数而不是连接 SQL 字符串(特别是在处理用户输入时) - 使用连接会导致 SQL 注入攻击和会破坏 SQL 的字符(例如名称中的撇号)。它还使空值更易于处理。

如果我进行这些更改,您的代码将不再是这样:

String connectionString = "Data Source=*******;Initial Catalog=MaleFemale;Integrated Security=True";

public MainWindow()
{
    InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        string sql = "insert into TableMaleFemale(Name,EiD,Gender) values (@Name, @EiD, @Gender)"
        using(SqlCommand cmd = new SqlCommand(sql, connection))
        {
            cmd.Parameters.Add("@Name").Value   = NametextBox.Text == null   ? DBNull.Value : NametextBox.Text;
            cmd.Parameters.Add("@EiD").Value    = EiDtextBox.Text == null    ? DBNull.Value : EiDtextBox.Text;
            cmd.Parameters.Add("@Gender").Value = GendertextBox.Text == null ? DBNull.Value : GendertextBox.Text;
            connection.Open();
            cmd.ExecuteNonQuery();
        }
        con.Close();
    }
}

这三件事都不能解决您提出的问题,但它会解决您尚未解决的其他问题。

【讨论】:

  • 解决OP还没有解决的问题
  • 显然我不能再说+1,但这就是我想说的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 2011-08-03
相关资源
最近更新 更多