如果不为null,则插入数据库

时间:2013-06-02 18:44:56

标签: c# database sql-server-2008-r2

我正在尝试创建一个表单,以便插入到数据库中,表单中的任何内容都不能为空值。作为一种输入方法,我正在使用文本框和组合框。

  using (SqlConnection con = new SqlConnection("Data Source=HRC0;Initial Catalog=users;Integrated Security=True"))
  using (SqlCommand sc = new SqlCommand("if NOT NULL ('" + txtIme.Text + "'," + 
        txtGodina.Text + ",'" + cmbZanr.SelectedItem + "','" + txtRedatelj.Text + "'," + 
        txtTrajanje.Text + ",'" + txtIMDB.Text + "'," + cmbPosuden.SelectedItem + ",'" + 
        txtTrailer.Text + "') insert into filmovi (Ime, Godina, Žanr, Redatelj, " + 
        "[Trajanje (min)], imdb_link, Posuđen , Trailer) values " + 
        "(@Ime, @Godina, @Žanr, @Redatelj,@[Trajanje (min)]," + 
        "@imdb_link,@Posuđen @Trailer )", con))
        {
            con.Open();
            sc.Parameters.AddWithValue("@Ime", txtIme.Text);
            sc.Parameters.AddWithValue("@Godina", txtGodina.Text);
            sc.Parameters.AddWithValue("@Žanr", cmbZanr.SelectedItem);
            sc.Parameters.AddWithValue("@Redatelj", txtRedatelj.Text);
            sc.Parameters.AddWithValue("@[Trajanje (min)]", txtTrajanje.Text);
            sc.Parameters.AddWithValue("@imdb_link", txtIMDB.Text);
            sc.Parameters.AddWithValue("@Posuđen", cmbPosuden.SelectedItem);
            sc.Parameters.AddWithValue("@Trailer", txtTrailer.Text);

            int o = sc.ExecuteNonQuery();
            if (o == -1)
            {
                MessageBox.Show("You didn't fill in all the textboxes!");
                this.Hide();
                new Dodaj().Show();
            }
            else
            {
                MessageBox.Show("The movie was added!");
                con.Close();
                this.Hide();
                new AdminMod().Show();
            }
        }
    }

我希望有人可以帮我修复这段代码。

2 个答案:

答案 0 :(得分:2)

您可以在执行null之前检查query值。像这样的东西

if(!String.IsNullOrWhiteSpace(txtIme.Text) && !String.IsNullOrWhiteSpace(txtGodina.Text)....
{
   // do your work
}

else
{
   MessageBox.Show("You didn't fill in all the textboxes!");
   this.Hide();
   new Dodaj().Show();
}

答案 1 :(得分:0)

IF NOT NULL不是sql命令的有效语法。在执行查询之前,应在C#代码中完成此检查。并为命令使用简单的名称。不需要与字段名称进行一对一匹配

// To simplify your code put the checks in a private function that return true if the
// the inputs are okay or false if not....
if(CheckValidInputs())
{
    using (SqlConnection con = new SqlConnection(.......)
    // Just the insert statement
    using (SqlCommand sc = new SqlCommand("insert into filmovi " + 
          "(Ime, Godina, Žanr, Redatelj, " + 
          "[Trajanje (min)], imdb_link, Posuđen , Trailer) values " + 
          "(@Ime, @Godina, @Žanr, @Redatelj, @Trajanje," + 
          "@imdb,@Posuđen @Trailer)", con))
    {
        ... execute and check the return
    }
}
else
   ... message for invalid inputs