Home > database >  Get value from a var
Get value from a var

Time:11-05

I've got this piece of code and I need to get the value of a specific column from the database.

using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
    var sql = "select * from "   tablename   " where ID = "   itemid;
    var data1 = cnn.QuerySingle(sql)
}

And I know that It can be done like this

string s = data1.ColumnName;

But is there a way for me to set the column reference programmatically as below?

string test = "Column1";
string s = data1.test;

CodePudding user response:

This looks like Dapper. In which case, you can cast the row from this to IDictionary<string, object>, and use the indexer.

var map = (IDictionary<string,object>)data1;
var value = map[columnName];

Note that the comments are right, and you should parameterize this query. You can't parameterize the table name, though:

var sql = "select * from "   tablename   " where ID = @itemid";
var data1 = cnn.QuerySingle(sql, new {itemid});
  • Related