P
P
postya2020-01-06 07:57:45
WPF
postya, 2020-01-06 07:57:45

How to put a variable in sqlite query?

I'm writing an application in C# + WPF
There is a comboboox that contains data from SQLIte DB tables.
I created a method that reads the database and puts data in a combobox, I will specify the name of the table in the method parameters.
The name of the table will be a string variable.
How to pass table name in sqlite query?
The query looks like this:
"SELECT ID FROM category1";
category1 should be the name of the variable
Here is what I tried to do, but it doesn't work:

private SQLiteConnection sqlCon;
        private SQLiteCommand sqlCommand;
        private SQLiteDataAdapter sqlDataAdapter;
        private DataSet ds = new DataSet();
        private DataTable dt = new DataTable();


        public void SetConnection()
        {
            sqlCon = new SQLiteConnection("Data Source=database.db;Version=3;New=False;Compress=True");
        }

public void ReadMyData(ComboBox comboBox, string category)
        {
            SetConnection();
            sqlCon.Open();
            
            sqlCommand.CommandText = "SELECT ID FROM @category";
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.Parameters["@name"].Value = category;
            
            sqlCommand = new SQLiteCommand(sqlCommand.CommandText, sqlCon);

            List<string> str = new List<string>();
            try
            {
                SQLiteDataReader sqReader = sqlCommand.ExecuteReader();
    
                // Always call Read before accessing data.
                while (sqReader.Read()) 
                {
                    str.Add(sqReader["ID"].ToString());
                    string questions = sqReader["ID"].ToString();
                    comboBox.Items.Add(questions);
                } 
                // always call Close when done reading.
                sqReader.Close();
            }
            finally
            {
                sqlCon.Close();
            }
        }

Calling a method in another class:
private Database db = new Database();

db.ReadMyData(comboQuestions, "category1");

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
HemulGM, 2020-01-06
@postya

:

sqlCommand.CommandText = "SELECT ID FROM :category";
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters["name"].Value = category;

So stop what? Table name?
Why, just concatenation does not suit you?
Horror ... Did you even understand what you wrote?
This is how it should be, I think.
sqlCommand.CommandText = "SELECT ID FROM category where name = :name";
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters["name"].Value = category;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question