【问题标题】:How to insert number which is from variable to sql database?如何将变量中的数字插入到sql数据库中?
【发布时间】:2018-04-25 12:36:45
【问题描述】:

我想做一个函数,它会生成带有 6 个随机数的乐透彩票,然后插入数据库。如果我写像 2, 10, 23... 之类的数字,可以并执行查询,但是如果我写像 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();


    }

【问题讨论】:

  • 您已将它们设为文本,但尚未将它们作为值插入,您可以执行 $"INSERT ... {lotto[0]},{lotto[1]}...." 或你最好将它们作为参数插入
  • "程序抛出错误" 你得到了什么错误?
  • 你做错了。您需要在 SQL 查询中使用命令参数,并且不要直接在其中使用变量名。
  • 可能是重复的问题。我建议您在问这样的问题之前搜索一个好的教程并了解更多关于如何在 C# 中创建查询的知识。作为一个起点,我可以推荐这个:stackoverflow.com/questions/19956533/…

标签: c# mysql sql database insert


【解决方案1】:

我建议您使用 SQL 命令的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();
}

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    相关资源
    最近更新 更多