[英]Mysql primary key id issues
基本上我正在做一個系統,用戶輸入姓名、電子郵件、密碼和用戶類型,這些輸入將保存到我的本地數據庫中。 我正在嘗試創建一個自動生成和遞增 ID 的主鍵 ID,因此對於第一個輸入 1、第二個 2、第三個 3 等。
相反,我得到了一堆字母和隨機數,如下所示; d7a8675a-c7cf-406a-983f-370d5b96fa62
這是我在 Visual Studio 數據庫設計器上寫的內容
CREATE TABLE [dbo].[Users] (
[Id] int IDENTITY(1,1) PRIMARY KEY,
[UserName] NCHAR (50) NULL,
[Email] NCHAR (50) NULL,
[Password] NCHAR (50) NULL,
[Role] NCHAR (15) NULL
);
另外我忘了提到,當我訪問我的 Register.aspx 頁面時,用戶可以在其中填寫要插入數據庫的字段,我在單擊注冊按鈕時調用以下內容,是否會導致問題我的 SQL 代碼?
String insertQuery = "insert into Users (Id,UserName,Email,Password,Role) values (@Id ,@Uname ,@email ,@password ,@role)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("@Id", newGUID.ToString());
com.Parameters.AddWithValue("@Uname",TextBoxUN.Text);
com.Parameters.AddWithValue("@email", TextBoxEmail.Text);
com.Parameters.AddWithValue("@password", TextBoxPass.Text);
com.Parameters.AddWithValue("@role", DropDownListRole.SelectedItem.ToString());
首先將表定義更改為:
CREATE TABLE [dbo].[Users] (
[Id] int IDENTITY(1,1) PRIMARY KEY NOT NULL,
[UserName] NCHAR (50) NULL,
[Email] NCHAR (50) NULL,
[Password] NCHAR (50) NULL,
[Role] NCHAR (15) NULL
);
和你的代碼:
String insertQuery = "insert into Users (UserName,Email,Password,Role) values (@Uname ,@email ,@password ,@role)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("@Uname",TextBoxUN.Text);
com.Parameters.AddWithValue("@email", TextBoxEmail.Text);
com.Parameters.AddWithValue("@password", TextBoxPass.Text);
com.Parameters.AddWithValue("@role", DropDownListRole.SelectedItem.ToString());
您需要跳過保存com.Parameters.AddWithValue("@Id", newGUID.ToString());
並允許IDENTITY
填充值。
你的主鍵定義錯誤試試這個:
CREATE TABLE [dbo].[Users] (
[Id] int NOT NULL AUTO_INCREMENT,
[UserName] NCHAR (50) NULL,
[Email] NCHAR (50) NULL,
[Password] NCHAR (50) NULL,
[Role] NCHAR (15) NULL,
PRIMARY KEY (id)
);
編輯后編輯:
為什么要填寫一個新的 GUID 作為 id 參數?
很清楚為什么你將這些隨機字符串作為你的 id ......如果你定義了 id 來自動增加數字,你就不必指定 id 參數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.