considering an sqlite table like this :
+--------------+-----------+--------------+ -----------+
| Col1(string) | Col2(int) | Col3(double) | ... |
+--------------+-----------+--------------+------------+
| A_string | B_int | C_double | ... |
+--------------+-----------+--------------+------------+
The ... means hunderts of more columns. Currently, we get the data from the table in c# like this:
using( SQLiteConnection con = new SQLiteConnection( databaseConnectionString ) )
{
con.Open(); //Open connection
using( SQLiteCommand cmd = new SQLiteCommand( "SELECT * FROM table", con ) )
{
var dataTable = new DataTable();
using( var sqlDataAdapter = new SQLiteDataAdapter( cmd ) )
{
sqlDataAdapter.Fill( dataTable );
if( dataTable.Rows.Count > 0 ) //ensure, there are some results
{
foreach( DataRow row in dataTable.Rows )
{
//Now initialize the c# objects
//But we do not wannt to hardcode every cast,
//cause the type information is already in the database
//therefore the function "getColumnValueAsRuntimeType()" is used to get the runntime type
string a = getColumnValueAsRuntimeType( "Col1", row );
int b = getColumnValueAsRuntimeType( "Col2", row );
double c = getColumnValueAsRuntimeType( "Col3", row );
...
}
}
}
}
}
private dynamic getColumnValueAsRuntimeType( string columnName, DataRow row )
{
int index = row.Table.Columns.IndexOf( columnName );
Type castTo = row.Table.Columns[ index ].DataType.UnderlyingSystemType;
if( typeof( Int64 ) == castTo )
{
return Convert.ChangeType( row[ columnName ], typeof( Int32 ) );
}
return Convert.ChangeType( row[ columnName ], castTo );
}
Now there are some performance issues due to the call of :
int index = row.Table.Columns.IndexOf( columnName );
Type castTo = row.Table.Columns[ index ].DataType.UnderlyingSystemType;
at the function "getColumnValueAsRuntimeType()"
So my main question is :
- What is the fastest/performantest way to get data from an sqlite database table in c# ? Without hardcoding every typcast in the source (We dont wannt to recompile the source everytime a database type is changed. The database should be the master). And why do i have to cast anyway? I am using a c# class to access the database, the data should already be typed.
We are talking here about an sqlite table with 1000 columns and million of rows.