我有一列中有一個“非常小的值”的 sqlite 表。像 0.00000363455000。當我在“DB Browser for SQlite”中運行查詢時,值顯示正確:
SQlite 1 的螢屏截圖資料庫瀏覽器

在我的 c# 應用程式中,小值始終為 0。
using (SQLiteConnection connection = new SQLiteConnection(
"Data Source='" dmaDataSource "'"))
{
SQLiteCommand command = new SQLiteCommand(sqlQuery, connection);
connection.Open();
SQLiteDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
response = new DmaResponse();
while (reader.Read())
{
Type t0 = reader.GetFieldType(0); // is decimal
Type t1 = reader.GetFieldType(1); // is decimal
string f0 = reader.GetName(0);
string f1 = reader.GetName(1);
response.price_per_ton = (decimal)reader[0];
string test = reader[1].ToString(); // "0"
response.price_per_mm3 = (decimal)reader[1]; // 0.00000363455000 becomes 0
}
}
}

有任何想法嗎?
經過更多測驗:
這兩個欄位都是 NUMERIC 型別:
在 c# 中是十進制。

在創建這篇文章之前,我嘗試了 GetDecimal 方法。
response.price_per_ton = reader.GetDecimal(0);
string test = reader[1].ToString();
response.price_per_mm3 = reader.GetDecimal(1);
GetDecimal(0) 有效,GetDecimal(1) 拋出例外:{“輸入字串格式不正確。”}
然后我使用 DB Browser 將“我的”行格式中的小數點分隔符更改為 .

現在, reader.GetDecimal(1) 不再拋出例外,而是回傳 0。
uj5u.com熱心網友回復:
根據sqlite 的檔案,基本資料型別是:
- 64 位有符號整數
- 64 位 IEEE 浮點數
- 細繩
- 斑點
- 無效的
在您的情況下,它將是一個 64 位 IEEE 浮點數。
Microsoft.Data.Sqlite.Core 庫(請注意,我假設您正在使用它),如果您在閱讀器上使用 GetDecimal,則對 GetString 的結果使用 decimal.Parse 。
這意味著該欄位作為字串檢索,導致值從數字自動轉換為文本,然后使用 decimal.Parse 轉換回數字。這有很多可能出錯的方法。
如果您使用 GetDouble,則在驅動程式中使用原生方法 sqlite_column_double,并且不會進行轉換(因此我希望沒有無效格式)。
雙精度不如小數精確,因此您可能希望在使用它進行計算之前將雙精度轉換為小數。
為了盡可能減小誤差,將小數作為字串存盤在資料庫中,這樣可以避免任何自動轉換(但將使用更多位元組來存盤相同的資料)。
uj5u.com熱心網友回復:
我越來越接近它:
ServerVersion = "3.37.0"
Column[1]是型別,System.Decimal期望值為0.00000363455000。
reader[1].ToString()回傳"0"
(decimal) reader[1] 回傳0
reader.GetDecimal(1)拋出例外:
輸入字串的格式不正確。
reader.GetString(1)回傳"0,00000363455000"(德語小數分隔符)
,我可以將其轉換為十進制。
現在我有了我的期望值,但我不知道為什么。
uj5u.com熱心網友回復:
您并沒有真正正確地使用閱讀器。您應該使用閱讀器的方法來正確檢索值。在這種情況下,“GetDecimal”方法:
response.price_per_ton = reader.GetDecimal(0);
response.price_per_mm3 = reader.GetDecimal(1);
此處的方法資訊:https:https://docs.microsoft.com/en-us/dotnet/api/microsoft.data.sqlite.sqlitedatareader.getdecimal ? view=msdata-sqlite-6.0.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485332.html
下一篇:根據其他列填充列-SQLITE
