如果不为空,则插入数据库
本文关键字:插入 数据库 如果不 | 更新日期: 2023-09-27 18:16:24
我试图使一个表单插入到一个数据库中,在表单中没有什么可以是空值。作为一种输入方法,我使用文本框和组合框。
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();
}
}
}
我希望有人能帮我修复这段代码。
您可以在执行query
之前简单地检查null
的值。像这样
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();
}
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