【发布时间】:2018-07-01 14:03:36
【问题描述】:
我正在使用 Visual Studio 2008 和 SQL Server 2008,我有一个表
bookdat 包含这些列:
title varchar(200), author varchar(100), publication varchar(200),
accno varchar(200) not null primary key, price int, quantity int
现在在 Visual Studio 中,我正在创建一个搜索数据库函数,用户可以使用任何一列(从复选框)搜索任何数据,并在文本框中输入值以在数据库表中查找该数据。
当我搜索 accno、价格和数量时,此功能效果很好。 但是在搜索标题、作者、出版物时会抛出异常。
我什至尝试将值相应地转换为字符串或整数(使用convert.tostring 等),但没有成功。
我的 C# 代码在这里(我已经在公共类中声明了 SqlConnection con、SqlCommand 和 SqlDataAdapter):
private void button3_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBox2.Text) && !string.IsNullOrEmpty(textBox8.Text))
{
cmd = new SqlCommand("SELECT * FROM bookdat WHERE title=@fdata OR author=@fdata OR publication=@fdata OR accno=@fdata OR price=@fdata OR quantity=@fdata", con);
if (comboBox2.SelectedIndex == 0)
cmd.Parameters.AddWithValue("@fdata", textBox8.Text);
else if (comboBox2.SelectedIndex == 1)
cmd.Parameters.AddWithValue("@fdata", textBox8.Text);
else if (comboBox2.SelectedIndex == 2)
cmd.Parameters.AddWithValue("@fdata", textBox8.Text);
else if (comboBox2.SelectedIndex == 3)
cmd.Parameters.AddWithValue("@fdata", textBox8.Text);
else if (comboBox2.SelectedIndex == 4)
cmd.Parameters.AddWithValue("@fdata", textBox8.Text);
else if (comboBox2.SelectedIndex == 5)
cmd.Parameters.AddWithValue("@fdata", textBox8.Text);
da = new SqlDataAdapter(cmd);
try
{
DataTable dt = new DataTable();
con.Open();
da.Fill(dt);
cmd.ExecuteNonQuery();
dataGridView2.DataSource = dt;
con.Close();
if (dt.Rows.Count> 0)
{
MessageBox.Show("Record Found!!");
comboBox2.Text = "";
textBox8.Text = "";
}
else
{
MessageBox.Show("No Records Found!!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
MessageBox.Show("Please Fill The Required Fields To Find Data !!");
}
}
【问题讨论】:
-
你为什么使用一堆嵌套的 if 语句,它们都做同样的事情?那应该是一个单一的声明。但实际上您的代码永远不会工作,因为您使用单个参数来搜索各种数据类型。您确实应该为每个可搜索的属性使用不同的参数。然后使用包罗万象的查询类型来查找数据。 sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries 使用 AddWithValue 一定要小心...blogs.msmvps.com/jcoehoorn/blog/2014/05/12/…
-
@Sami 我不是;
-
对我的问题投反对票,为什么??
标签: c# sql-server sql-server-2008 exception