这段代码有什么问题?我想从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();
}
答案 0 :(得分:2)
cmd.CommandText = "select max(remain) from item_new_customer where cust='" + textBox2.Text + "'";
答案 1 :(得分:1)
您对SQL-Injection是开放的,使用参数来避免它。
要回答您的实际问题,我假设您想要此列: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();
}
答案 2 :(得分: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 injection的公开邀请。
答案 3 :(得分: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();