1

So I have a in-memory database and I'm trying to insert data into the table and it's not working. Am I doing something wrong?

var connection = new SQLiteConnection("DataSource=:memory:;Version=3;New=True;");

connection.Open();

string sql = "CREATE TABLE  recently_viewed(movieid INTEGER,picture TEXT)";

SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteNonQuery();

using ( command = connection.CreateCommand())
{
    command.CommandText = "INSERT into recently_viewed(movieid ,picture) values(@movieid,@picture)";
    command.Prepare();
    command.Parameters.AddWithValue("@movieid", id);
    command.Parameters.AddWithValue("@picture", picture);
}

string   count_table = " SELECT count(*) FROM recently_viewed";

SQLiteCommand   com3 = new SQLiteCommand(count_table, connection);

int   ctable = Convert.ToInt32(com3.ExecuteScalar().ToString());

Response.Write(ctable);

connection.Close();
1
  • "It's not working" is not a description of a problem. Please tell us what doesn't work, what happens when you run it, and any exceptions you get. Commented Aug 17, 2015 at 19:13

1 Answer 1

2

I just noticed from your code that this line:

command.ExecuteNonQuery();

is called only once. What happens when you do:

var connection = new SQLiteConnection("DataSource=:memory:;Version=3;New=True;");

connection.Open();

string sql = "CREATE TABLE  recently_viewed(movieid INTEGER,picture TEXT)";

SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteNonQuery();

using ( command = connection.CreateCommand())
{
    command.CommandText = "INSERT into recently_viewed(movieid ,picture) values(@movieid,@picture)";
    command.Prepare();
    command.Parameters.AddWithValue("@movieid", id);
    command.Parameters.AddWithValue("@picture", picture);
    command.ExecuteNonQuery();
}


string   count_table = " SELECT count(*) FROM recently_viewed";

SQLiteCommand   com3 = new SQLiteCommand(count_table, connection);
com3.ExecuteNonQuery();

int   ctable = Convert.ToInt32(com3.ExecuteScalar().ToString());

Response.Write(ctable);

connection.Close();
Sign up to request clarification or add additional context in comments.

1 Comment

Put the second ExecuteNonQuery inside the using block; after that block command will be Disposed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.