0

I would like to ask you where I have problem in my code? I want to insert data to SQLite. Thank you

private void button1_Click(object sender, EventArgs e)
{
    con.Open();
    if (textBox1.Text == "Pirulau")
    {
        SQLiteCommand cmd22 = con.CreateCommand();
        cmd22.CommandType = CommandType.Text;
        cmd22.CommandText = "insert into Pirulau(Dátum opravy, Dodávateľ, Názov náhradného dielu, Číslo náhradného dielu, Cena)values('"+textBox2.Text+"', '"+textBox3.Text+"', '"+textBox4.Text+"', '"+textBox5.Text+"', '"+textBox6.Text+")";
        cmd22.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SQLiteDataAdapter da = new SQLiteDataAdapter(cmd22);
        da.Fill(dt);
        dataGridView1.DataSource = dt;
    }
    con.Close();
}

enter image description here

Fildor
  • 12,873
  • 4
  • 34
  • 64

2 Answers2

2

Spaces in table/column/etc. names are a famously bad idea. But you can use them if you really want to, you just need to tell the query engine that you're doing it. To "escape" table/column/etc. names in SQLite, wrap them in double-quotes:

insert into Pirulau("Dátum opravy", "Dodávateľ", "Názov náhradného dielu", "Číslo náhradného dielu", "Cena") ...

As an aside, your code is wide open to SQL injection, which is not only a security vulnerability but also a very common source of bugs. You should use query parameters instead, which treat user-modifiable values as values instead of as potentially executable code.

Cleptus
  • 3,302
  • 4
  • 28
  • 33
David
  • 188,958
  • 33
  • 188
  • 262
  • Thank you very much. It is running already ,but I had to use ' ' instead " " . Could you explain me your comment: "As an aside, your code is wide open to SQL injection, which is not only a security vulnerability but also a very common source of bugs. You should use query parameters instead, which treat user-modifiable values as values instead of as potentially executable code." I am beginner with SQL databases and I would like to know more about it. Thank zou very much – Matej Kmetty Jun 01 '22 at 19:52
  • @MatejKmetty For a fun explanation on SQL Injection, you can google "Bobby tables" or "exploits of a mom". Think about what would happen if the user typed as a surname `O'hara` or what an evil user could do to your application. – Cleptus Jun 03 '22 at 06:37
0

The sql request syntax is not valid. The columns where whom name contains spaces are not valid, they need to be wrapped into a " ".

insert into Pirulau("Dátum opravy", Dodávateľ, "Názov náhradného dielu", "Číslo náhradného dielu", Cena) ...
Hervé
  • 266
  • 6