Click here to Skip to main content
15,892,072 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to check the existence of a table in SQLite and if the table exist I need to insert some values to that table .

I have tries the below code and its not inserting the values to the database

What I have tried:

try
            {
                sqlconnection = DBConnection.GetDBConnetion();
                sqlconnection.Open();
                string query = "SELECT name FROM sqlite_master WHERE type='table' AND name='Users';";
                SQLiteCommand cmd = new SQLiteCommand(query);
                cmd.CommandType = CommandType.Text;
                cmd.Connection = sqlconnection;
                cmd.ExecuteNonQuery();
                var result = cmd.ExecuteReader();
                if (result.HasRows)
                {      
                    try
                    {
                        if (result != null)
                        {
                            result.Close();
                        }

                        cmd.CommandText = "INSERT INTO [Users] (ID ) VALUES ( @ID  )";
                        cmd.Parameters.AddWithValue("@ID", 1);
                     

                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
Posted
Updated 17-Mar-21 0:10am
v5

1 solution

You forgot to call the most important method: SqliteCommand.ExecuteNonQuery Method (Microsoft.Data.Sqlite) | Microsoft Docs[^]

C#
sqlconnection.Open();
string query = "SELECT name FROM sqlite_master WHERE type='table' AND name='Users';";
SQLiteCommand cmd = new SQLiteCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlconnection;
cmd.ExecuteNonQuery(); //removed from here!
var result = cmd.ExecuteReader();
if (result.HasRows)
{      
	try
	{
		cmd.CommandText = "INSERT INTO [Users] (ID ,Name ,Password) VALUES ( @ID , @Name , @Password )";
		cmd.Parameters.AddWithValue("@ID", 1);
		cmd.Parameters.AddWithValue("@Name", 1);
		cmd.Parameters.AddWithValue("@Password", 1);
        cmd.ExecuteNonQuery(); //... and added here!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900