Anon Proxy Anon Proxy - 3 months ago 89
C# Question

Login form with SQLite in C#

I'm having a problem making a loginform with sqlite in C#. this is the code

SQLiteConnection connectionstring;
connectionstring = " Data Source = C:\Crystal Management\Crystal Management\bin\Debug\Konaku.db; Version = 3 ";
public void LoadData()
{
try
{
SQLiteCommand SelectCommand = new SQLiteCommand("SELECT `Username`, `Password` FROM `LoginData` WHERE `Username` = '" + flatTextBox1.Text + "' AND `Password` = '" + flatTextBox2.Text + "'", connectionstring);
SQLiteDataReader myReader;
connectionstring.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
Base bs = new Base();
bs.Show();
this.Hide();
connectionstring.Close();
}
else if (count == 0)
{
flatAlertBox1.kind = FlatUI.FlatAlertBox._Kind.Error;
flatAlertBox1.Text = "data not right";
connectionstring.Close();

}
else
{

}
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
connectionstring.Close();
}
}


it is showing error in this line of code

connectionstring = " Data Source = C:\\Crystal Management\\Crystal Management\bin\\Debug\\Konaku.db; Version = 3 ";


message error is : Cannot implicitly convert type 'string' to 'Finisar.SQLite.SQLiteConnection'

what can I do with this?

Answer

This is the proper way to query SQL. Always use "using" for disposable class like SQLiteConnection, SQLiteCommand, and SQLiteDataReader. Use parameterized queries to avoid sql injection.

public void LoadData()
{
  try
  {
    using (var conn = new SQLiteConnection(@"Data Source=C:\Crystal Management\Crystal Management\bin\Debug\Konaku.db;Version=3"))
    {
      conn.Open();
      using (var cmd = new SQLiteCommand("SELECT Username,Password FROM LoginData WHERE Username='@username' AND Password = '@password'", conn))
      {
        cmd.Parameters.AddWithValue("@username", flatTextBox1.Text);
        cmd.Parameters.AddWithValue("@password", flatTextBox2.Text);
        using (var reader = cmd.ExecuteReader())
        {
          var count = 0;
          while (reader.Read())
          {
            count = count + 1;
          }
          if (count == 1)
          {
            Base bs = new Base();
            bs.Show();
            Hide();
          }
          else if (count == 0)
          {
            flatAlertBox1.kind = FlatUI.FlatAlertBox._Kind.Error;
            flatAlertBox1.Text = "data not right";
          }
        }
      }
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}
Comments