[英]C#: How to get data from the last row in database? I'm using in visual studio 2017
Need help in C# ( Visual Studio 2017 ) 在C#中需要帮助(Visual Studio 2017)
I want to get a data from my database from the last row or last inputted data. 我想从数据库的最后一行或最后输入的数据中获取数据。 My code is here..
我的代码在这里。
String query = "SELECT TOP(1) MessageNumber FROM ncslbpHighWay";
SqlCommand SDA = new SqlCommand(query, AR);
SqlDataReader data = SDA.ExecuteReader();
if (data.Read())
{
textBox2.Text = data.GetValue(0).ToString();
}
AR.Close();
I already got the data but from the specific column at the top only. 我已经获得了数据,但是仅从顶部的特定列中获取。 I don't know how to get the bottom value.
我不知道如何获得最低价值。 Also i tried the
DESC
but it doesn't work. 我也尝试了
DESC
但它不起作用。
String query = "SELECT TOP(1) MessageNumber FROM ncslbpHighWay ORDER BY COLUMN DESC";
This is my first question here in Stackoverflow. 这是我在Stackoverflow中的第一个问题。 I hope someone would help me on this.
我希望有人能帮助我。
you can use orm. 您可以使用orm。 Things will become easy.
事情会变得容易。
Considering your question below snippet can help you. 在代码段下方考虑您的问题可以为您提供帮助。
-- Method 01--
SELECT * FROM TestData where ID =(Select Max(ID) from TestData)
-- Method 02--
SELECT top 1 * FROM TestData order by ID Desc;
Here I have consider ID columns as Auto Increment. 在这里,我将ID列视为“自动增量”。
Your specified query below works for SQL Server for getting last value in table: 您在下面指定的查询适用于SQL Server以获取表中的最后一个值:
SELECT TOP(1) MessageNumber FROM ncslbpHighWay ORDER BY [ColumnName] DESC
However since you're mentioning MySQL tag (implying you're using MySQL instead of SQL Server), you need to use LIMIT n
after ORDER BY
instead, where n is the number of returned results, ie 1 for single result: 但是,由于您提到的是MySQL标记(这意味着您使用的是MySQL而不是SQL Server),因此需要在
ORDER BY
之后使用LIMIT n
,其中n是返回结果的数量,即单个结果为1:
SELECT MessageNumber FROM ncslbpHighWay ORDER BY [ColumnName] DESC LIMIT 1
-- or using offset:
SELECT MessageNumber FROM ncslbpHighWay ORDER BY [ColumnName] DESC LIMIT 0, 1
If you're using MySql.Data.MySqlClient.MySqlConnection
instead using standard System.Data.SqlClient.SqlConnection
, you can write data retrieval like this: 如果使用的是
MySql.Data.MySqlClient.MySqlConnection
而不是标准的System.Data.SqlClient.SqlConnection
,则可以编写数据检索,如下所示:
using (MySqlConnection AR = new MySqlConnection())
{
AR.Open();
String query = "SELECT MessageNumber FROM ncslbpHighWay ORDER BY [ColumnName] DESC LIMIT 1";
using (MySqlCommand SDA = new MySqlCommand(query, AR))
{
MySqlDataReader data = SDA.ExecuteReader();
if (data.Read())
{
textBox2.Text = data.GetValue(0).ToString();
}
}
AR.Close();
}
NB: I recommend you using ORM (eg Entity Framework) with MySQL Connector .NET library to enable LINQ functionality when managing database queries. 注意:建议您在管理数据库查询时,将ORM(例如,实体框架)与MySQL Connector .NET库一起使用以启用LINQ功能。
Similar issues: 类似问题:
How to select the last record from MySQL table using SQL syntax 如何使用SQL语法从MySQL表中选择最后一条记录
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.