I am doing a c# project with sqlite as database, the problem I am having is that the csv…
- User
I am doing a c# project with sqlite as database, the problem I am having is that the csv exporter is writing negative numbers beccause the getvalue doesn't take into account that integer in sqlite can have long values.
Here is a real database value: 20180101062818 11 01/01/2018 06:28:18 01/01/2018 20:07:38 0 0 22.0 0.0 1690.0 0.0 0.0 0.0 1712.0 0.0 0.0 0.0 0.0 0.0 150.0 0.0 0.0 0.0 0.0 0.0 1862.0 1862.0 20180101200738
Here is the written value: -1950261086,11,"01/01/2018 06:28:18","01/01/2018 20:07:38",0,0,22,0,1690,0,0,0,1712,0,0,0,0,0,150,0,0,0,0,0,1862,1862,"","","",-1950123166
and here is my code to export to csv file:
using (var connection = new SQLiteConnection(connectionString)) { connection.Open(); using (var command = new SQLiteCommand("SELECT * FROM {tableName}", connection)) { using (var reader = command.ExecuteReader()) { var csv = new StringBuilder(); var headers = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray(); csv.AppendLine(string.Join(",", headers)); while (reader.Read()) { var values = Enumerable.Range(0, reader.FieldCount) .Select(i => reader.GetValue(i)) .Select(v => v is string ? ""{v}"" : v) .ToArray(); csv.AppendLine(string.Join(",", values)); } File.WriteAllText(filePath, csv.ToString()); } } }
How can I fix this problem?
- Assistant
The issue you are facing is because the
GetValue()method of the SQLiteDataReader returns the values as objects. In the code you provided, these objects are directly converted to strings for CSV export.To handle long integer values correctly, you can check if the value is of type
longand convert it to a string manually. Here's an updated version of your code with the necessary modification:using (var connection = new SQLiteConnection(connectionString)) { connection.Open(); using (var command = new SQLiteCommand($"SELECT * FROM {tableName}", connection)) { using (var reader = command.ExecuteReader()) { var csv = new StringBuilder(); var headers = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray(); csv.AppendLine(string.Join(",", headers)); while (reader.Read()) { var values = Enumerable.Range(0, reader.FieldCount) .Select(i => reader.GetValue(i)) .Select(v => v is string ? $"\"{v}\"" : (v is long ? ((long)v).ToString() : v)) .ToArray(); csv.AppendLine(string.Join(",", values)); } File.WriteAllText(filePath, csv.ToString()); } } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.