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 に答える