如何在c#中编写SQL命令

时间:2016-04-05 11:03:18

标签: c# sql

我有一个关于使用Windows窗体中的给定语句搜索数据库的项目,但我无法编写用于搜索SQL的正确命令。我的代码:

int? value;
if (this.textBox2.Text == "" || this.textBox2.Text == null)
    value = null;
else
    value = Convert.ToInt32(this.textBox2.Text);
    SqlCommand command = new SqlCommand(
        @"SELECT * 
          FROM Billing 
            INNER JOIN Payment ON Payment.payment_id = Billing.billing_type 
            INNER JOIN Customer ON Customer.customer_id = Billing.billing_customer
          WHERE  billing_id like '%" + textBox5.Text.ToString() + "%' 
            AND billing_type like '%" + comboBox2.SelectedValue + "%'
            AND Billing.billing_cost > " + value + "", connection);
    SqlDataReader reader = command.ExecuteReader();

问题是,当我输入3000到textBox2(我控制它正在读3000)时,搜索不起作用并且什么都不显示。也没有例外。

我是否写过命令?

2 个答案:

答案 0 :(得分:0)

尝试使用参数:

string query =  @"SELECT * 
          FROM Billing 
            INNER JOIN Payment ON Payment.payment_id = Billing.billing_type 
            INNER JOIN Customer ON Customer.customer_id = Billing.billing_customer
          WHERE  billing_id like '%" + textBox5.Text.ToString() + "%' 
            AND billing_type like '%" + comboBox2.SelectedValue + "%'
            AND Billing.billing_cost > @value", connection);

SqlCommand command = new SqlCommand(query,connection);

command.Parameters.Add("@value",SqlDbType.Int);
command.Parameters["@value"].Value = Convert.ToInt32(this.textBox2.Text);
SqlDataReader reader = command.ExecuteReader();

取自What are good ways to prevent SQL injection?

答案 1 :(得分:-1)

试试这个

"select * From Billing INNER JOIN Payment ON Payment.payment_id = Billing.billing_type 
INNER JOIN Customer ON Customer.customer_id = Billing.billing_customer
where billing_id like '%'+'" + textBox5.Text + "'+'%' 
    and billing_type like '%'+'" + comboBox2.SelectedValue + "'+'%' 
    and Billing.billing_cost > " + value
  1. 在符号'
  2. 之前和之后使用字符%
  3. 提示。切勿将数据转换为相同的数据类型。 MSDN表示,与确切编码相比,它的执行速度可降低7倍。提到你对textBox5.Text.ToString()的使用。它错了,因为它已经是一个字符串。