Introduction
Have you ever tried to conn.SetPassword(yourPassword)
and see it doesn't work? Well, I did in my project and tried some methods to set a password to my SQLite database. However SetPassword()
method doesn't seem to be working as it should. You also must open the database, close it and reopen before calling ChangePassword()
method. By this way, you can encrypt your SQLite passwords.
Background
As it's a pain to open, close, reopen and change the password manually, I wanted to create an application that does these for me. After adding more controls, I wanted to share it with you.
Using the Code
The application itself doesn't contain so much complex data or methods, however I'll explain the main ones.
TestConnection(string strFileName)
method checks whether the application can connect to the database with given information. That's why we need the table name in the beginning. strFileName
parameter contains the file name of the database (obviously), and connectionFailed
variable is a boolean which checks whether the connection has ever failed since the beginning of the first run. This is because, if you enter an encrypted database without providing a password, it will become true
and the application will warn you about what has happened.
private void TestConnection(string strFileName)
{
conn = new SQLiteConnection();
if (!connectionFailed && string.IsNullOrEmpty(txtPassword.Text))
{
conn = new SQLiteConnection(string.Concat("Data Source=", strFileName));
}
else
{
conn = new SQLiteConnection(string.Concat
("Data Source=", txtPath.Text, ";Password=", txtPassword.Text, ";"));
}
conn.Open();
try
{
var command = conn.CreateCommand();
command.CommandText = string.Format("select * from {0}", txtTableName.Text);
command.ExecuteNonQuery();
command.ExecuteScalar();
if (conn.State == ConnectionState.Open)
{
lblStatus.Text = "Connected";
lblStatus.ForeColor = Color.Green;
}
else
{
MessageBox.Show("Couldn't establish a connection with the database.
If it's password protected, please specify the password in the password field.",
"Errör");
connectionFailed = true;
}
}
catch (Exception ex)
{
MessageBox.Show("Couldn't establish a connection with the database.
If it's password protected, please specify the password in the password field.",
ex.Message);
lblStatus.Text = "Disconnected";
lblStatus.ForeColor = Color.Red;
connectionFailed = true;
}
}
History
First version. I'm open to new ideas that could be added to the project.