1

这段代码有什么问题?我想从 SQL 行中捕获最后一个值并将其显示在TextBox. 请帮助我。

private void textBox2_Leave(object sender, EventArgs e)
{
    cmd.Connection = cn;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select last(remain) from item_new_customer where cust=" + textBox2.Text + "";
    float h = (float)cmd.ExecuteScalar();
    textBox20.Text = h.ToString();
}
4

4 回答 4

2
cmd.CommandText = "select max(remain) from item_new_customer where cust='" + textBox2.Text + "'";
于 2013-01-28T12:39:36.520 回答
1

您对 SQL 注入开放,使用参数来避免它。

为了回答你的实际问题,我假设你想要这个专栏:remain。但是您想要最后插入的记录的值。由于您没有提到检测插入顺序的列,因此我使用主键列(不推荐):

string sql = "SELECT TOP 1 remain FROM dbo.tablename WHERE cust=@cust ORDER BY id DESC";
using(var con = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(sql, con))
{
    cmd.Parameters.AddWithValue("@cust", textBox2.Text);
    con.Open();
    double h = (double)cmd.ExecuteScalar();
    textBox20.Text = h.ToString();
}
于 2013-01-28T12:45:42.957 回答
0

非常感谢所有我最后的正确代码是:

cmd.Connection = cn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select top 1(remain) from item_new_customer where cust='"+textBox2.Text+"' order by id desc";
        int h = (int)cmd.ExecuteScalar();
        textBox20.Text = h.ToString(); 
于 2013-01-29T11:29:56.540 回答
0

您在 : 之后缺少单引号textBox2.Text

private void textBox2_Leave(object sender, EventArgs e)
{
    cmd.Connection = cn;
    cmd.CommandType = CommandType.Text;


    cmd.CommandText = 
   "select max(remain) from item_new_customer where cust=" + textBox2.Text + "'";
                                                          //Missing tick here ^ 
    float h = (float)cmd.ExecuteScalar();
    textBox20.Text = h.ToString();
}

此外,您的代码是SQL 注入的公开邀请。

于 2013-01-28T12:40:39.220 回答