如何将变量中的数字插入sql数据库?

wxclj1h5  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(390)

我想做一个函数,它将生成6个随机数字彩票,然后插入数据库。如果我写2,10,23这样的数字。。。etc是可以执行查询的,但是如果我编写名称变量,比如lotto[0],lotto[1]。。。程序抛出错误。谢谢你的帮助。

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();

    }
siotufzp

siotufzp1#

我建议你用 Parameters 如下所示:

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();
}

相关问题