-1

I would like to do a function, which will generate lotto ticket with 6 random numbers and later insert into database. If I write numbers like 2, 10, 23... etc, is ok and query is executed, but if I write name variable like lotto[0], lotto[1]... program thrown an error. Thanks for Your help.

    private void button1_Click(object sender, EventArgs e)
    {
        int check = 0;
        int[] lotto = new int[6];
        Random rand = new Random();
        for (int i = 0; i < lotto.Length;)
        {
            check = rand.Next(1, 49);
            if (!lotto.Contains(check))
            {
                lotto[i] = check;
                i++;
            }
        }


        string insertQuery = "INSERT INTO kupony VALUES(NULL, 1, lotto[0], lotto[1], lotto[2], lotto[3], lotto[4], lotto[5], -1, '2018-04-25', -1)";
        connection.Open();
        MySqlCommand command = new MySqlCommand(insertQuery, connection);
        try
        {
            if (command.ExecuteNonQuery() == 1)
            {
                //MessageBox.Show("Data Inserted");
            }
            else
            {
                //MessageBox.Show("Data Not Inserted");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }


        connection.Close();


    }
Rand Random
  • 7,300
  • 10
  • 40
  • 88
gushy22
  • 9
  • 6
  • 1
    you have made them as text, you havent inserted them as values you can either do $"INSERT ... {lotto[0]},{lotto[1]}...." or you would do better to insert them as parameters – BugFinder Apr 25 '18 at 12:38
  • "program thrown an error" **What** error do you get? – MakePeaceGreatAgain Apr 25 '18 at 12:38
  • You're doing it wrong. You need to use command parameters in your SQL Query and don't use variable names directly into it. – CodeNotFound Apr 25 '18 at 12:39
  • Possibly a duplicate question. I recommend you to search a good tutorial and learn a little bit more on how to create queries in C# before asking a question like this one. As a starting point, I can recommend this: https://stackoverflow.com/questions/19956533/sql-insert-query-using-c-sharp – sɐunıɔןɐqɐp Apr 25 '18 at 12:43

1 Answers1

2

I recommend you to use Parameters of the SQL Command like below:

string query = "INSERT INTO test_table (column1, column2) VALUES (?column1,?column2);";
cn.Open();
using (MySqlCommand cmd = new MySqlCommand(query, cn))
{
    cmd.Parameters.Add("?column1", MySqlDbType.Int32).Value = 123;
    cmd.Parameters.Add("?column2", MySqlDbType.VarChar).Value = "Test";
    cmd.ExecuteNonQuery();
}
Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46