mardi 27 janvier 2015

insert data to SQLite with button_click in C#

I want to insert data to SQLite with my WPF project, and I hope after I click a button, I could save a data into the SQLite, here's my code.



private void AddToDB_Click(object sender, RoutedEventArgs e)
{
sqlite_Conn = new SQLiteConnection("Data Source=database.db;Version=3;New=True;Compress=True;");

sqlite_Conn.Open();

sqlite_Cmd = sqlite_Conn.CreateCommand();

sqlite_Cmd.CommandText = "CREATE TABLE test (id integer primary key, text varchar(100));";

sqlite_Cmd.ExecuteNonQuery();

sqlite_Cmd.CommandText = "INSERT INTO test (id, text) VALUES (1,'Test Text 1');";

sqlite_Cmd.ExecuteNonQuery();

sqlite_Cmd.CommandText = "SELECT * FROM test";

sqlite_DataRdr = sqlite_Cmd.ExecuteReader();

while (sqlite_DataRdr.Read())
{
System.Console.WriteLine(sqlite_DataRdr["text"]);
}

sqlite_Conn.Close();
}


And my problem is, no matter how many times I click the button, it will store only 1 data, and I think the problem is because I create a new table after I click the button each time, so I change my code to :



if (!created)
{
sqlite_Cmd.CommandText = "CREATE TABLE test (id integer primary key, text varchar(100));";
sqlite_Cmd.ExecuteNonQuery();
created = true;
}


but it get worse, it could only execute successfully for 1 time, in the second time I press the button to insert data, the program will stop at



sqlite_Cmd.ExecuteNonQuery();


after



sqlite_Cmd.CommandText = "SELECT * FROM test";


and showed {"no such table: test"} error.


Does anyone have any good idea to solve this? Thanks alot!


Aucun commentaire:

Enregistrer un commentaire