简体   繁体   English

C# WPF:使用自动增量将数据插入数据库的问题

[英]C# WPF : problem with inserting data to database with auto increment

I want to do a register page, so I want to insert new account into my database.我想做一个注册页面,所以我想将新帐户插入我的数据库。 I have database in Microsoft SQL Server Management Studio.我在 Microsoft SQL Server Management Studio 中有数据库。 Table Accounts has these columns:Accounts具有以下列:

user_id PK, int, not null, username, password

The problem is with user_id , it is set to auto increment, so I wanted to run a SQL query like this in Oracle:问题在于user_id ,它设置为自动递增,所以我想在 Oracle 中运行这样的 SQL 查询:

INSERT INTO Accounts (user_id, username, password) 
VALUES (NULL, 'test', 'testpass');

So I write this code:所以我写了这段代码:

sqlCmd.CommandText = "INSERT INTO [Accounts](user_id, username, password) VALUES (NULL, @regUser, @regPass)";

But I get an error:但我收到一个错误:

Cannot insert the value NULL into column 'user_id', table 'NoteAppDB.dbo.Accounts': column does not allow nulls.无法将值 NULL 插入列“user_id”、表“NoteAppDB.dbo.Accounts”:列不允许空值。 INSERT fails.插入失败。 The statement has been terminated.该语句已终止。

I cannot allow nulls in SQL Server Management Studio, because user_id is the primary key.我不能在 SQL Server Management Studio 中允许空值,因为user_id是主键。

This is the rest of the code:这是代码的其余部分:

xaml: xml:

<StackPanel Margin="30" Name="StackRegister" Visibility="Hidden">
    <Label Content="Register"  Foreground="White" FontSize="50" HorizontalAlignment="Center" />
    <Separator></Separator>
    <Label Content="Username" Foreground="White" />
    <TextBox Name="txtRegUsername" Background="#545d6a" Foreground="White" FontSize="35"/>
    <Label Content="Password" Foreground="White" />
    <PasswordBox Name="txtRegPassword" Background="#545d6a" Foreground="White" FontSize="35"/>
    <Label Content="Repeat password" Foreground="White" />
    <PasswordBox Name="txtRegPass" Background="#545d6a" Foreground="White" FontSize="35"/>
    <Button Name="btnReg" Click="btnReg_Click" Content="Register" Margin="70,15,70,10" Background="#545d6a" Foreground="White" FontSize="35" />
</StackPanel>

c#: C#:

SqlConnection sqlCon = new SqlConnection(@"Data Source=DESKTOP-32HBHCQ; Initial Catalog=NoteAppDB; Integrated Security=True;");

try
{
    if (sqlCon.State == ConnectionState.Closed)
        sqlCon.Open();

    String query = "SELECT COUNT(1) FROM Accounts WHERE username = @user";

    SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
    sqlCmd.CommandType = CommandType.Text;
    sqlCmd.Parameters.AddWithValue("@user", txtRegUsername.Text);

    int count = Convert.ToInt32(sqlCmd.ExecuteScalar());

    if(txtRegPassword.Password != txtRegPass.Password)
    {
        MessageBox.Show("Username exists in database or passwords are different!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        txtRegUsername.Text = "";
        txtRegPassword.Password = "";
        txtRegPass.Password = "";
    }
    else if (count == 0)
    {
        sqlCmd.CommandText = "INSERT INTO [Accounts](user_id, username, password)values(NULL,@regUser,@regPass)";
        sqlCmd.Parameters.AddWithValue("@regUser", txtRegUsername.Text);
        sqlCmd.Parameters.AddWithValue("@regPass", txtRegPassword.Password);
        sqlCmd.Connection = sqlCon;
        int a = sqlCmd.ExecuteNonQuery();

        if (a == 1) 
            MessageBox.Show("New user created!", "Success", MessageBoxButton.OK, MessageBoxImage.Information);

        StackRegister.Visibility = Visibility.Hidden;
        StackLogin.Visibility = Visibility.Visible;
    }
    else 
    {
        MessageBox.Show("Username exists in database or passwords are different!", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
        txtRegUsername.Text = "";
        txtRegPassword.Password = "";
        txtRegPass.Password = "";
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
finally
{
    sqlCon.Close();
}

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. ( https://www.w3schools.com/sql/sql_autoincrement.asp ). https://www.w3schools.com/sql/sql_autoincrement.asp )。 This means that you do not have to supply a user_id value (be it NULL or an INTEGER ) when creating a new user Accounts entry because the table will supply one itself.这意味着您在创建新的用户帐户条目时不必提供 user_id 值(无论是NULL还是INTEGER ),因为该表将自己提供一个。 That is why you get a SQL error.这就是您收到 SQL 错误的原因。

Since it's an "auto-increment" column (which in SQL Server is a column with an IDENTITY attribute), you must NOT include it in your INSERT statement.由于它是一个“自动增量”列(在 SQL Server 中是具有IDENTITY属性的列),因此您不能将它包含在您的INSERT语句中。

Try this:尝试这个:

INSERT INTO Accounts (username, password) 
VALUES ('test', 'testpass');

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

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