如何选择自动增量标识列,其值必须在另一个表中使用。 [英] How can i select an autoincremented identity column whose value have to be used in another table.

查看:42
本文介绍了如何选择自动增量标识列,其值必须在另一个表中使用。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hai ..

例如我有2个表person1,数据将person1的id设置为autoincremented,并且当描述添加到表时,还有另一列名为description的应该插入到表中第二个表data.whose值与person1中的id相同。请帮助我...这里附上代码..

提前致谢..



hai..
For example i have 2 tables person1,data the id of person1 is set as autoincremented and there is another column named description when description is added to table desc id should be inserted to the second table data.whose value is same as id in person1.can u please help me...Here am attaching the code..
Thanks in advance..

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=book;User ID=sa;Password=nest123@!");
            con.Open();


            string query = "insert into person1(description) values('" + textBox3.Text + "')";
            
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();

            try
            {
                SqlCommand cm = new SqlCommand("select Id from person1 where description='" + textBox3.Text + "'",con);
                SqlDataReader rd = cm.ExecuteReader();

                while (rd.Read())
                {
                    string str = rd["Id"].ToString();

                }
                SqlCommand cmd2 = new SqlCommand("insert into data (name,age,desc_id) values('" + textBox1.Text + "','" + textBox2.Text + "','+str+')");
            }

            catch (SqlException ex)
            {
            }
        }
        
    }
}

推荐答案

在C#中,SQL语句写入SELECT SCOPE_IDENTITY(); 所以你的代码是:



In C#, right after your SQL Statement write "SELECT SCOPE_IDENTITY();" so your code would be:

Insert into TABLE (...) values (...); SELECT SCOPE_IDENTITY();



而不是ExecuteNonQuery()使用ExecuteScalar()。

ie,


Instead of ExecuteNonQuery() use ExecuteScalar().
i.e.,

Decimal id = (Decimal)cmd.ExecuteScalar(); // You can now use Id for your further insert statements.



看看它是否有效。


See if it works.


请不要这样做!不要连接字符串以构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。改为使用参数化查询。



其次,最简单的方法是使用一个命令:



Please, do not do it like that! Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

Secondly, the easiest way to do that is to use a single command:

using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("INSERT INTO MyTable (myColumn1, myColumn2) VALUES ('XXX', 666) SELECT SCOPE_IDENTITY()", con))
        {
        decimal d = (decimal) com.ExecuteScalar();
        }
    }

d 将包含您刚刚分配的ID。

d will contain the ID you just assigned.


这篇关于如何选择自动增量标识列,其值必须在另一个表中使用。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆