-1

我试图制作一个用于插入数据库的表单,其中表单中的任何内容都不能是空值。作为一种输入方法,我使用文本框和组合框。

  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();
            }
        }
    }

我希望有人可以帮助我修复此代码。

4

2 回答 2

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();
}
于 2013-06-02T18:48:46.850 回答
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
于 2013-06-02T18:50:26.877 回答