【问题标题】:Retrieve data from a another table and insert into a another从另一个表中检索数据并插入另一个表
【发布时间】:2021-06-12 11:04:20
【问题描述】:

我正在尝试根据 ID 号从表中检索数据并将其插入到另一个表中。程序在 C# 中,数据库在 MySQL 中。

检索表名是student_dt,我要插入的表名是student_att

这是我目前正在做的事情

 private void button1_Click(object sender, EventArgs e)
    {
        cmd = new MySqlCommand();
        cmd.CommandText = "Insert into student_att values(`id`, `nic`, `name`, `address`, `number`, `batch`)";
        string Query1 = "select * from student_dt where id like '" + textBox1.Text + "%'";
        if (textBox1.Text == "")
        {
            MessageBox.Show("Please provide all data");
        }
        else
        {
            con.Open();
            cmd.Connection = con;
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("Data Inserted");

            string Query = "select * from student_att ;";
            MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
            MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
            MyAdapter.SelectCommand = MyCommand2;
            DataTable dTable = new DataTable();
            MyAdapter.Fill(dTable);
            dataGridView2.DataSource = dTable;

        }

【问题讨论】:

  • 首先,请阅读:Bobby-tables.com,并且在您的生活中再也不会(曾经)使用字符串连接将用户提供的值插入到原始 SQL 命令中。永远不需要它,它是被黑客入侵、被解雇或两者兼而有之的头号方法之一
  • 第二,完全不需要下载数据。 MySQL 将很乐意运行 INSERT INTO t(a,b,c) SELECT x,y,z FROM u WHERE col=@val 形式的查询来将这 3 列从 U 复制到 T,对于任何 COL 值为 @val 的行

标签: c# mysql vba c#-4.0


【解决方案1】:

您可以从一个查询中完成

string query = "insert into student_att (`id`, `nic`, `name`, `address`, 
`number`, `batch`) select * from student_dt where id like '" + textBox1.Text + "%'"

【讨论】:

  • 不,不要让 SQL 注入的问题长期存在。向 OP 展示如何正确操作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 2020-09-28
  • 2014-02-17
相关资源
最近更新 更多