Created
February 20, 2015 09:36
-
-
Save szunyog/7f5c059886ef4312c7cf to your computer and use it in GitHub Desktop.
sqlite check column exists c#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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.
Thank you for the explanation.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.