从表C#中检索ID

时间:2017-02-13 12:42:58

标签: c# sql sql-server

我想要检索' ReceiverID'来自接收者'插入时的表格 a' Cname'当我填写访问者表时,将ID放入访问者。 我该如何检索此ID?我可以在我的数据库中找到它但我想要它自动。填写访客表。 (我是所有这一切的新手)

        try
        {
            string connStr = ConfigurationManager.ConnectionStrings["ParkingBase"].ConnectionString;

            using (SqlConnection connection = new SqlConnection(connStr))
            {
                connection.Open();
                SqlCommand cmd = connection.CreateCommand();
                cmd.CommandType = CommandType.Text;

                string Cname = TxtCname.Text;
                string FirstName = TxtFname.Text;
                string MiddleName = TxtMname.Text;
                string LastName = TxtLname.Text;
                string PhoneNumber = TxtPhoneNumber.Text;
                //(some variable for ReceiverID)

                cmd.CommandText = "INSERT INTO Receiver(Cname) " +
                    "values('" + Cname + "')";
                cmd.ExecuteNonQuery();

                cmd.CommandText = "INSERT INTO Visitor(FirstName, MiddleName, LastName, PhoneNumber,ReceiverID)" +
                    "values('" + FirstName + "', '" + MiddleName + "', '" + LastName + "', '" + PhoneNumber + "','"ReceiverID"')";
                cmd.ExecuteNonQuery();
                connection.Close();
            }
        }
        catch (Exception)
        {
            throw;
        }
    }`

3 个答案:

答案 0 :(得分:2)

您应该在第一次插入后编写附加SELECT SCOPE_IDENTITY()的参数化查询。通过这些简单的查询,无需编写存储过程,并且有两点需要担心维护。

cmd.CommandText = "INSERT INTO Receiver(Cname) values(@cname);
                   SELECT SCOPE_IDENTITY()";
cmd.Parameters.Add("@cname", SqlDbType.NVarChar).Value = cName;
int receiverID = Convert.ToInt32(cmd.ExecuteScalar));

现在您可以编写第二个插入语句(再次使用参数化查询)

cmd.Parameters.Clear();
cmd.CommandText = @"INSERT INTO Visitor
       (FirstName, MiddleName, LastName, PhoneNumber,ReceiverID)
       values(@first, @middle, @last,@phone,@receiver)";
cmd.Parameters.Add("first", SqlDbType.NVarChar).Value = FirstName;
....
cmd.Parameters.Add("receiver", SqlDbType.Int).Value = receiverID;
cmd.ExecuteNonQuery();

答案 1 :(得分:1)

您可以在插入后更改注释测试并使用范围标识,然后使用ExecuteScalar()来获取此ID。在这种情况下最好使用SP。

    /// change here 

           cmd.CommandText = "INSERT INTO Receiver(Cname) " +
                "values('" + Cname + "') ;select SCOPE_IDENTITY()"; 
         var newID= Convert.ToInt32( cmd.ExecuteScalar());

     --- better solution suggested by Steve is below -- I didnt tested this but this is approach .

 using (var cmd = new SqlCommand(@"INSERT INTO Receiver(Cname) VALUES (@cname)", conn))
    {
        cmd.Parameters.AddRange(
            new[]
                {
                    new SqlParameter(@"cname", SqlDbType.VarChar).Value = cname
                });
        conn.Open();
        cmd.ExecuteNonQuery();
    }

答案 2 :(得分:1)

您的代码疯狂容易受到SQLInjection攻击 - 有人能够在您的文本框中输入SQL并在数据库中执行它。

您可以通过将所有内容转换为存储过程或使用参数化查询来解决此问题和实际问题。

要在插入后获取身份,请使用SCOPE_IDENTITY()方法。

你的存储过程看起来像这样(注意我不知道你的数据类型,所以我猜一点):

CREATE PROC dbo.InsertVisitor
   @CName NVARCHAR(100),
   @FName NVARCHAR(100),
   @MName NVARCHAR(100),
   @LName NVARCHAR(100),
   @PhoneNumber NVARCHAR(100)
AS
BEGIN
    DECLARE @receiverId INT

    INSERT INTO Cname (Receiver) VALUES (@CName)
    SET @receiverId = SCOPE_IDENTITY();

    INSERT INTO Visitor (FirstName, MiddleName, LastName, PhoneNumber,ReceiverID)
    VALUES(@FName,@MName,@LName,@PhoneNumber,@receiverId)
END 

对代码的更改只是转换为调用存储过程而不是内联sql

SqlCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.InsertVisitor";
cmd.Parameters.Add("@CName",SqlDbType.NVarChar).Value = TxtCname.Text;
// snip.. other parameters
cmd.ExecuteNonQuery();