Wednesday 7 July, 2010

BASIC INSERT AND SELECT COMMANDS FOR SQLITE IN .NET

  1. Our "SAVE" button click code looks like the following:
  2. private void button1_Click(object sender, EventArgs e)
  3. {
  4. SQLiteTransaction trans;
  5. string SQL = "INSERT INTO PERSONS (ID, FIRSTNAME,LASTNAME,EMAIL,PHONE) VALUES";
  6. SQL += "(@ID, @firstname, @lastname, @email, @phone)";
  7. SQLiteCommand cmd = new SQLiteCommand(SQL);
  8. cmd.Parameters.AddWithValue("@ID", Guid.NewGuid());
  9. cmd.Parameters.AddWithValue("@firstname", this.txtFirst.Text);
  10. cmd.Parameters.AddWithValue("@lastname", this.txtLast.Text);
  11. cmd.Parameters.AddWithValue("@email", this.txtEmail.Text);
  12. cmd.Parameters.AddWithValue("@phone", this.txtPhone.Text);
  13. cmd.Connection = sqLiteConnection1;
  14. sqLiteConnection1.Open();
  15. trans = sqLiteConnection1.BeginTransaction();
  16. int retval = 0;
  17. try
  18. {
  19. retval= cmd.ExecuteNonQuery();
  20. if (retval == 1)
  21. MessageBox.Show("Row inserted!");
  22. else
  23. MessageBox.Show("Row NOT inserted.");
  24. }
  25. catch (Exception ex)
  26. {
  27. trans.Rollback();
  28. }
  29. finally
  30. {
  31. trans.Commit();
  32. cmd.Dispose();
  33. sqLiteConnection1.Close();
  34. }
  35. }
  36. Finally, our "DISPLAY" button click handler code looks like this:
  37. private void button2_Click(object sender, EventArgs e)
  38. {
  39. string SQL = "SELECT * FROM PERSONS";
  40. SQLiteCommand cmd = new SQLiteCommand(SQL);
  41. cmd.Connection = sqLiteConnection1;
  42. SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
  43. DataSet ds = new DataSet();
  44. try
  45. {
  46. da.Fill(ds);
  47. DataTable dt = ds.Tables[0];
  48. this.dataGridView1.DataSource = dt;
  49. }
  50. catch (Exception ex)
  51. {
  52. }
  53. finally
  54. {
  55. cmd.Dispose();
  56. sqLiteConnection1.Close();
  57. }
  58. }

No comments:

Post a Comment