0

我正在使用自动编号,但它对我不起作用。我想在我的 StudentID 号码中自动编号。

OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = 
"insert into Student(ID, Lastname, Middlename, Firstname, Address, DateofBirth, Birthplace, Contact_number, emailaddress, guardian_name, Guardian_contact) values ('" + txtStudentIDnumber.Text + "','" + txtlastname.Text + "','" + txtfirstname.Text + "','" + 
txtmiddlename.Text + "','" + txtaddress.Text + "','" + txtdateofbirth.Text + "','" + txtbirthplace.Text + "','" + txtcontactnumber.Text + "','" + txtemailaddress.Text + "','" + txtGuardianname.Text + "','" + txtguardiancontact.Text + "')";
system.Connection = mydatabase;



if (MessageBox.Show("Save data?", "Confirm Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
4

3 回答 3

2

首先,您应该像这样指定身份列:

在此处输入图像描述

然后你的代码:

 OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\db.accdb");
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = string.Format("insert into Student(LastName,...) values('{0}',...)",txtLastName.Text.Trim(),...);
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
于 2012-09-19T07:05:09.293 回答
2

如果没有数据库架构或错误消息,很难确定问题。但是,问题可能是因为您尝试在列中插入一个值,而该ID列可能启用了自动编号(也称为计数器)。改变:

system.CommandText = "insert into Student(ID, Lastname, ..."; // And so on

system.CommandText = "insert into Student(Lastname, ..."; // And so on

还要考虑将查询更改为参数化查询(例如在's' 附近的不正确语法中提到的查询。字符串 ')' 后的非闭合引号)而不是使用连接来避免 SQL 注入和转义问题。

于 2012-09-19T06:39:25.240 回答
0

您的 ID 列应该设置为一个身份(在数据库中),然后您应该从插入中省略它。

http://forums.asp.net/t/1492834.aspx/1

更新

我怀疑您的 StudentIdNumber 是一个实际的州颁发的 ID 号,而您正在寻找的是一个身份字段。

您需要使用用于创建表的表设计器或使用脚本向表中添加标识列

CREATE TABLE Student(
   ID int identity, 
   StudentIdNo varchar(10), 
   Lastname varchar(10), 
   Firstname varchar(10), 
   Middlename varchar(10), 
   CONSTRAINT AutoIncrementTest_PrimaryKey PRIMARY KEY (ID)
)

这将是您的插入语句的格式,请注意没有 ID 字段

"INSERT INTO Student (StudentIdNo, Lastname, Firstname, Middlename) VALUES (?)"

...在您的情况下,添加身份字段后

   OleDbCommand comm = new OleDbCommand();
   comm.CommandType = CommandType.Text;

   comm.CommandText = 
       @"insert into Student(StudentIdNo, Lastname, Firstname, Middlename) 
                     values (@StudentIdNo, @Lastname, @Firstname, @Middlename)"; 

   comm.Parameters.AddWithValue("@StudentIdNo", txtStudentIdNo.Text);
   comm.Parameters.AddWithValue("@Lastname", txtlastname.Text);
   comm.Parameters.AddWithValue("@Firstname", txtfirstname.Text);
   comm.Parameters.AddWithValue("@Middlename", txtmiddlename.Text);

   comm.Connection = mydatabase;
于 2012-09-19T06:41:18.607 回答