简体   繁体   English

使用C#WPF和SQL添加行时的自动增量值

[英]Auto increment value on adding a row using C# WPF and SQL

I'm working with C# WPF in Visual Studio Express 2012. I've created a local service-based database ( .mdf database). 我正在Visual Studio Express 2012中使用C#WPF。已经创建了一个基于本地服务的数据库( .mdf数据库)。

I've created a table with 我创建了一个表

    CREATE TABLE [dbo].[Scenes] (
         [id]              INT           IDENTITY (1, 1) NOT NULL,
         [Planning_period] NVARCHAR (50) NOT NULL,
         [Scene_name]      NVARCHAR (50) NOT NULL,
         PRIMARY KEY CLUSTERED ([id] ASC)
    );

I want to be able to add a new row but the following code doesn't work because I'm leaving id as null. 我希望能够添加新行,但是以下代码无法正常工作,因为我将id保留为null。 How do I get it to increment automatically when I add data? 添加数据时如何使它自动递增?

    SqlConnection cn = new SqlConnection(global::WaterfowlModel.Properties.Settings.Default.WAMConnectionString);
    try
    {
        string sql = "INSERT INTO Scenes (Planning_period, Scene_name) Values ('" + working_plan + "','" + Create_plan_txt.Text +"')";
        SqlCommand cmd = new SqlCommand(sql, cn);
        cn.Open();
        cmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
    }
    finally
    {
        cn.Close();
    }

Thanks! 谢谢!

EDIT 编辑

I've attempted this with a stored procedure as well and received the same error. 我也尝试通过存储过程进行此操作,并收到相同的错误。

CREATE PROCEDURE [dbo].[Add_Scene]
    @param1 nvarchar(50),
    @param2 nvarchar(50)
AS
    INSERT INTO Scenes(Planning_period, Scene_name)
    VALUES(@param1, @param2)

and code: 和代码:

        string sql = "Add_Scene";
        SqlCommand cmd = new SqlCommand(sql, cn);
        SqlParameter planname = new SqlParameter("@param1", working_plan);
        SqlParameter scenename = new SqlParameter("@param2", Create_plan_txt.Text);

        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(planname);
        cmd.Parameters.Add(scenename);
        cn.Open();
        cmd.ExecuteNonQuery();

First you should be carefull using that code, you should user parameters for the sqlCommand, and not made a concatenation... 首先,您应该谨慎使用该代码,应该为sqlCommand使用用户参数,而不要进行串联...

Second to work with the database you should see how to make the call, not using the sql Insert statement, but calling a stored procedure, that insert the record on the table, and holds the Insert statement. 其次,与数据库一起使用,您应该看到如何进行调用,而不是使用sql Insert语句,而是调用存储过程,该过程将记录插入表并保存Insert语句。

So resuming, if you see how to do what I answered you, you'll see that once you have the stored procedure working fine, you will be able to made the auto increment without worries ;). 因此,继续进行下去,如果您了解如何回答我的问题,那么您将看到,一旦存储过程运行良好,就可以自动进行递增;而不必担心;)。

And you win in all, because you code will be more robust, secure and reliable. 您将赢得一切,因为您的代码将更加健壮,安全和可靠。

Greetings. 问候。

I followed instructions found Create stored procedure to add with auto increment as its primary field? 我遵循发现的说明创建要添加自动增量作为其主要字段的存储过程?

One thing I had to do was rebuild the solution before Starting the application. 我要做的一件事是在启动应用程序之前重建解决方案。 Before I rebuilt it didn't work. 在我重建之前,它不起作用。

With the change you have made, you just need to return the ID in the Stored Procedure after the Insert, you have cupple of ways to do that, but be carefull... 进行更改后,只需在插入后返回存储过程中的ID,您便有足够的方法来执行此操作,但要小心...

If you do not have lots of traffic in your database you can use just this, is more faster: 如果您的数据库中没有很多流量,则可以使用此方法,这样会更快:

CREATE PROCEDURE [dbo].[Add_Scene]
    @param1 nvarchar(50),
    @param2 nvarchar(50)
AS
BEGIN
    INSERT INTO Scenes(Planning_period, Scene_name)
    VALUES(@param1, @param2)

    RETURN @@IDENTITY
END

This is a standard for this type of Stored Procedure, as you can see here: http://technet.microsoft.com/en-us/library/ms187342.aspx . 这是这种类型的存储过程的标准,您可以在这里看到: http : //technet.microsoft.com/zh-cn/library/ms187342.aspx However this function may not return the correct value, if you are working in a environment with lots of database traffic, it just return the ID of the last Insert operation, if there is concurrency, you may have problems, so check for other options, that may be slower in execution but more reliable. 但是,此函数可能无法返回正确的值,如果您在数据库流量很大的环境中工作,则它仅返回上一个Insert操作的ID,如果存在并发,则可能有问题,因此请检查其他选项,执行速度可能较慢,但更可靠。

The main point is to return from the database the ID auto incremented, after the insert, so you can read the value of the insert you made. 重点是从数据库中返回ID,该ID在插入后自动递增,因此您可以读取所做插入的值。

Hope that this helps you. 希望这对您有帮助。

Greetings. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM