簡體   English   中英

如何打印SQL Server的最后一條記錄

[英]how to print the last record of SQL server

我有一個數據庫名稱“ fees”,其中有4列(admno,收據編號,名稱,tutionfee)。 這里的主鍵是“收據號碼”。 我已經用不同的錄取編號輸入了幾條記錄。 也有幾個條目具有相同的入場號。 現在我只想只打印我輸入的最后一條記錄。 我該如何打印。 我已經編寫了代碼,但是第一條記錄正在打印。

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        con.Open();
        string str;  
str = "select * from fees where admno='" + temp + "'";
    SqlCommand com = new SqlCommand(str, con);
            SqlDataReader reader = com.ExecuteReader();
            reader.Read();
            TextBox1.Text = reader["admno"].ToString();
            TextBox2.Text = reader["receiptnumber"].ToString();
            TextBox3.Text = reader["name"].ToString();
            TextBox4.Text = reader["tutionfee"].ToString();

這應該做。 添加參數以避免sql注入! 您需要在ID DESC結尾處訂購並選擇第一個拳頭( TOP1

string Command = "select TOP 1 * from fees where admno = @admno ORDER BY receiptnumber DSEC";
using (SqlConnection mConnection = new SqlConnection(ConnectionString))
{
    mConnection.Open();
    using (SqlCommand cmd = new SqlCommand(Command, mConnection))
    {
        cmd.Parameters.Add(new MySqlParameter("@admno", temp));
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            reader.Read();
            TextBox1.Text = reader["admno"].ToString();
            TextBox2.Text = reader["receiptnumber"].ToString();
            TextBox3.Text = reader["name"].ToString();
            TextBox4.Text = reader["tutionfee"].ToString();
        }
    }
}

假設收據編號是一個標識字段,則可以select top 1 * from fees order by receiptnumber desc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM