Skip to content

Instantly share code, notes, and snippets.

@szunyog
Created February 20, 2015 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szunyog/7f5c059886ef4312c7cf to your computer and use it in GitHub Desktop.
Save szunyog/7f5c059886ef4312c7cf to your computer and use it in GitHub Desktop.
sqlite check column exists c#
private bool CheckIfColumnExists(string tableName, string columnName)
{
using(var conn = new SQLiteConnection("Data Source=mydb.sqlite;"))
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = string.Format("PRAGMA table_info({0})", tableName);
var reader = cmd.ExecuteReader();
int nameIndex = reader.GetOrdinal("Name");
while (reader.Read())
{
if (reader.GetString(nameIndex).Equals(columnName))
return true;
}
conn.Close();
}
return false;
}
@karennk
Copy link

karennk commented Feb 23, 2021

excellent!
1 thing confusing me is: int nameIndex = reader.GetOrdinal("Name");
it returns 1 and compare always with the given column name: if (reader.GetString(nameIndex).Equals(columnName))

for instance columnName is "abc" pls explain how it compares reader.GetString(nameIndex)1 with abc

Thanks in advance.

@szunyog
Copy link
Author

szunyog commented Feb 23, 2021

@karennk
reader.GetString expects an integer parameter, the index of the column in the result set.

In this case the index of the 'Name' column of the query PRAGMA table_info(mytable) is 1. So reader.GetString(nameIndex) will returns the value name of the column. This value is compared with the method parameter.

@karennk
Copy link

karennk commented Feb 28, 2021

Thank you for the explanation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment