我知道这是一个重复的问题,但我已经尝试了很多,但我得到了异常
- $ exception {" String未被识别为有效的DateTime。"} System.Exception {System.FormatException}
以下是我的代码,请查看并指导
SQL QUERY
SELECT gangId as gang,respectPoints as respectPoints,DATE_FORMAT(purchaseDate,'%d-%m-%Y')as date_purchase FROM tbl_gang t其中gangId =" + gangId
数据访问层代码
DataTable dt = new DataTable();
MySqlCommand cmd = conn.CreateCommand();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
cmd.CommandText = inAppPurchaseQuery;
da.Fill(dt)
排序代码
dt = gangRPObj.getGangRPLogsBL(gangId, fromDate, toDate);
var sortedTable = dt.AsEnumerable()
.OrderBy(r => DateTime.ParseExact(("date_purchase"),
"dd-mm-yyyy", null))
.CopyToDataTable();
由于
答案 0 :(得分:2)
您正在将字符串传递给日期时间转换,这就是异常即将发生的原因。试试
var orderedRows = from row in dt.AsEnumerable()
let date = DateTime.ParseExact(row.Field<string>("date_purchase"),"dd-mm-yyyy", null)
orderby date
select row;
答案 1 :(得分:1)
将日期列排序为字符串也无法正确排序。您还应该在数据库中而不是在内存中进行排序,并使用参数而不是字符串连接来防止sql-injection和date-conversion-issues这样的问题。
string sql = @"SELECT gangId as gang,
respectPoints as respectPoints,
DATE_FORMAT(purchasedDate, '%d-%m-%Y') as date_purchase,
FROM tbl_gang t
WHERE gangId=@gangId
ORDER BY purchasedDate ASC";
using (var cmd = new MySqlCommand(sql, conn))
using (var da = new MySqlDataAdapter(cmd))
{
da.SelectCommand.Parameters.Add("@gangId", MySql.Data.MySqlClient.MySqlDbType.Int32).Value = gangID;
da.Fill(dt); // no need to order this on client side
}