【问题标题】:how to use Loop in c# insert query [closed]如何在c#插入查询中使用循环[关闭]
【发布时间】:2015-08-13 17:49:56
【问题描述】:

我是一名职业高中的学生和新手程序员.. 我在插入查询中使用循环有一些问题.. 我有两个表,Book 和 Book_detail,与外键链接,我想将数据保存到两个表中,问题是每次我添加一本书时,我都有一个名为 copy_txt 的文本框,我的想法是我想保存book_detail 表中相同的 book_id 和相同的 location_id 但不同的 boookdetail_id 与我在copys_txt中插入的数量一样多。为了实现这一点,我尝试使用 for 循环,但我给了我错误

主键的重复条目

,这是我的完整代码

int copies = Convert.ToInt32(copies_txt.Text);                      
        int i;


        string constring = "datasource=localhost;port=3306;username=root;password=root";
        string Query = "insert into simbada_perpustakaan.book(book_id,title,release_date,genre,author,copies,create_by,create_date) values ('" + this.book_id.Text + "','" + this.title_txt.Text + "','" + this.time.Text + "','" + this.genre_txt.Text + "','" + this.author_txt.Text + "','" + this.copies_txt.Text + "','" + this.username_lbl.Text + "','" + DateTime.Now.ToString("yyyy/MM/dd/hh/mm/ss") + "') ; ";
        string Query2 = "insert into simbada_perpustakaan.book_detail(id_bookdetail,book_id,location_id) values('" + Guid.NewGuid() + "','" + this.book_id.Text + "','" + this.textBox1.Text + "') on duplicate key update id_bookdetail=(id_bookdetail=('"+Guid.NewGuid()+"'))";            
        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
        MySqlCommand cmdDataBase2 = new MySqlCommand(Query2, conDataBase);
        MySqlDataReader myReader;
        try
        {
            conDataBase.Open();
            myReader = cmdDataBase.ExecuteReader();
            conDataBase.Close();                
            for (i = 0; i <= copies; i++)
            {
                conDataBase.Open();
                myReader = cmdDataBase2.ExecuteReader();
                conDataBase.Close();              

            }              
            MessageBox.Show("saved"); 
            while (myReader.Read())
            {

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

谁能指出我的错误...谢谢。

【问题讨论】:

  • 在循环内多次插入查询 2。它的第一个值是 Guid.NewGuid() 这将是一个主键,你在循环之外分配它。所以总是相同的值..所以它会违反主键规则\
  • 哦...好的,谢谢,如果问的不是太多,您能提供一些解决方案吗?
  • 在那之前告诉我第二个表中是否存在相同的 GUID 你想做什么? bcos 在第二个查询中我可以看到on duplicate
  • 好吧,我不知道这是否是正确的查询,但这是目标......如果 GUID 已经存在于 book_detail 表中,我希望系统创建新的 GUID 并继续插入下一个值...
  • 好的理解那么你应该将查询放在循环中

标签: c# mysql loops


【解决方案1】:

我认为您的问题与第二个查询有关。将查询移入循环并检查。此外,您不需要数据阅读器,因为它是一个选择语句。您还可以避免多个数据库打开和关闭语句。试试下面的代码

int copies = Convert.ToInt32(copies_txt.Text);                      
        int i;
        string constring = "datasource=localhost;port=3306;username=root;password=root";
        string Query = "insert into simbada_perpustakaan.book(book_id,title,release_date,genre,author,copies,create_by,create_date) values ('" + this.book_id.Text + "','" + this.title_txt.Text + "','" + this.time.Text + "','" + this.genre_txt.Text + "','" + this.author_txt.Text + "','" + this.copies_txt.Text + "','" + this.username_lbl.Text + "','" + DateTime.Now.ToString("yyyy/MM/dd/hh/mm/ss") + "') ; ";

        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);

        MySqlDataReader myReader;
        try
        {
            conDataBase.Open();
           cmdDataBase.ExecuteNonquery();

            for (i = 0; i <= copies; i++)
            {

              string a = Guid.NewGuid().ToString();
              string Query2 = "insert into simbada_perpustakaan.book_detail(id_bookdetail,book_id,location_id) values('" + a + "','" + this.book_id.Text + "','" + this.textBox1.Text + "') on duplicate key update id_bookdetail=(id_bookdetail=('"+a+"'))"; 
               MySqlCommand cmdDataBase2 = new MySqlCommand(Query2, conDataBase);
               cmdDataBase2.ExecuteNonQuery();


            }              
            MessageBox.Show("saved"); 
            conDataBase.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

也总是尝试做参数化查询。这样可以避免sql注入问题。

【讨论】:

  • thx Sachu.... :) 它有效...
  • @JoshuaEgberio 欢迎朋友
【解决方案2】:

让,

first Guid.NewGuid() = 'zxcvbnm'

second Giud.NewGuid() = 'asdfghjkl'

book_id = 2

location_id = 3

执行 Query2 后,我们得到如下字符串

insert into book_detail(id_bookdetail,book_id,location_id) values('zxcvbnm','2'
,'3') on duplicate key update id_bookdetail='asdfghjkl';

当我们尝试在 for 循环中执行它时

When i = 0

它像id_bookdetail('zxcvbnm') is unique.一样插入数据

When i = 1

它还可以很好地插入数据,因为之前使用了 id_bookdetail('zxcvbnm'),但使用重复键 id_bookdetail set a new value('asdfghjkl') 这是唯一的。

But When i = 2

它会给您错误,因为首先他将id_bookdetaidid('zxvbnm') 作为重复项,然后他尝试使用同样重复的second one('asdfghjkl')。所以它会给你这个错误。

【讨论】:

  • If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed..如果我错了请纠正我
  • @Sachu,它不会更新任何前一行。它先插入 2 个,然后给出 duplicate key 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 2012-04-30
  • 1970-01-01
相关资源
最近更新 更多