in a c# sqlite project, my csv importer code is importing double values wrong. My csv…
- User
in a c# sqlite project, my csv importer code is importing double values wrong. My csv has the value 0,33 and it is importing 0 instead.
using (SQLiteTransaction transaction = sqliteConn.BeginTransaction()) { using (SQLiteCommand command = new SQLiteCommand(sqliteConn)) { foreach (System.Data.DataRow row in dataTable.Rows) { // Create the INSERT statement System.Text.StringBuilder insertQuery = new System.Text.StringBuilder(); insertQuery.Append($"INSERT INTO {tableName} ");
code// Build the column names System.Text.StringBuilder cols = new System.Text.StringBuilder(); foreach (System.Data.DataColumn column in dataTable.Columns) { cols.Append($"{column.ColumnName},"); } cols = cols.Remove(cols.Length - 1, 1); insertQuery.Append($"({cols}) "); // Build the parameter placeholders System.Text.StringBuilder values = new System.Text.StringBuilder(); foreach (System.Data.DataColumn column in dataTable.Columns) { values.Append($"@param_{column.ColumnName},"); command.Parameters.AddWithValue($"@param_{column.ColumnName}", row[column]); } values = values.Remove(values.Length - 1, 1); insertQuery.Append($"VALUES({values})"); // Execute the INSERT statement command.CommandText = insertQuery.ToString(); command.ExecuteNonQuery(); } } transaction.Commit(); } - Assistant
The issue is likely with how the double value is being stored in the DataTable. By default, the DataColumn.DataType property is set to System.Double, which expects decimal values to use a dot as the decimal separator.
To fix this issue, you can try changing the decimal separator in your csv file from a comma to a dot. If that is not possible or feasible, you can modify your code to parse the value as a decimal and then add it as a parameter to the SQLiteCommand.
Here's an example of how you can modify your code to handle decimal values correctly:
csharp