我有一个文本框表格,学生填写了他们的一般信息,如姓名,城市,州等等。有时学生不记得他们是否填写在之前的表单中,它将导致ms-access数据库中的重复条目。理想情况下,我希望代码首先在插入前在同一条记录上搜索ms-access数据库,查找匹配的名和姓。如果在输入的名字和姓氏字段上都有匹配的记录,那么脚本就会运行,并说出如下内容:“匹配记录已存在,您希望继续吗?”点击“是”将输入记录到一个新行中,点击“取消”根本不会将其输入到数据库中。插入前检查重复的条目(C#.net)
我开始这段代码,但我不确定它是否是正确的方向,任何指导将不胜感激,谢谢。
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = @FName AND [LName] = @LName", con))
{
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
(This is where I am stuck)
}
}
下面是提交按钮当前的代码。
protected void btnSubmit_Click(object sender, EventArgs e)
{
{
//Preforms insert statement on click to allow additions to the database
DateTime CurrentDate;
CurrentDate = DateTime.Now;
string constr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\sites\schoolinfo\students_dev\App_Data\Studentdb.mdb";
string cmdstr = "INSERT into StudentList(FName, LName, BDay, Gender, School, Grade, Address, APT, City, State, Zip, Email, Phone, CellPhone, ParentFName, ParentLName, ParentEmail) values(@FName, @LName, @BDay, @Gender, @School, @Grade, @Address, @APT, @City, @State, @Zip, @Email, @Phone, @CellPhone, @ParentFName, @ParentLName, @ParentEmail)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
{
con.Open();
}
//The following fields are added from the student information to the corresponding database fields
com.Parameters.AddWithValue("@FName", txtFirstName.Text);
com.Parameters.AddWithValue("@LName", txtLastName.Text);
com.Parameters.AddWithValue("@BDay", txtBirthDate.Text);
com.Parameters.AddWithValue("@Gender", ddlGender.Text);
com.Parameters.AddWithValue("@School", txtSchool.Text);
com.Parameters.AddWithValue("@Grade", txtGrade.Text);
//The following fields are added from the contact information to the corresponding database fields
com.Parameters.AddWithValue("@Address", txtAddress.Text);
com.Parameters.AddWithValue("@APT", txtApt.Text);
com.Parameters.AddWithValue("@City", txtCity.Text);
com.Parameters.AddWithValue("@State", ddlState.Text);
com.Parameters.AddWithValue("@Zip", txtZip.Text);
com.Parameters.AddWithValue("@Email", txtEmail.Text);
com.Parameters.AddWithValue("@Phone", txtPhone.Text);
com.Parameters.AddWithValue("@CellPhone", txtCellPhone.Text);
com.Parameters.AddWithValue("@ParentFName", txtParentFName.Text);
com.Parameters.AddWithValue("@ParentLName", txtParentLName.Text);
com.Parameters.AddWithValue("@ParentEmail", txtParentEmail.Text);
com.ExecuteNonQuery();
con.Close();
//End database connection
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Student has been successfully added!')", true);
}
}
表中的主键是什么?有没有可以检查的'StudentID'字段?如果是这样,我会提示他们输入他们的StudentID,运行一个查询来检查它是否存在,如果是/不是,就做你需要的。 – 2014-11-24 22:13:02