如何使用C#检查MySQL数据库中是否存在记录?
如果记录存在,窗体应显示一个消息框,说明该记录已经存在,并且不将值保存到数据库中。否则,应将新记录保存到数据库中。
它的C#语法是什么?我使用Visual Studio作为我的IDE。
private void btnSave_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;password=root";
string QueryAdd = "insert into assetmanagement.assets (`AssetId`,`AssetType`,`AssetDescription`,`SerialNumber`,`Barcode`,`Quantity`,`Manufacturer`,`Model`,`Category`,`Condition`,`Location`,`Department`,`DateAcquired`,`InService`,`Supplier`,`Notes`,`AddedBy`,`DateAdded`) values ('" + this.txtAssetId.Text + "','" + this.txtAssetType.Text + "','" + this.txtAssetDesc.Text + "','" + this.txtSerial.Text + "','" + this.txtBarcode.Text + "','" + this.txtQuantity.Text + "','" + this.txtManufacturer.Text + "','" + this.txtModel.Text + "','" + this.txtCategory.Text + "','" + this.txtCondition.Text + "','" + this.txtLocation.Text + "','" + this.txtDepartment.Text + "','" + this.txtDateAcquired.Text + "','" + this.txtInService.Text + "','" + this.txtSupplier.Text + "','" + this.txtNotes.Text + "','" + this.txtAddedBy.Text + "','" + this.txtDateAdded.Text + "') ;";
MySqlConnection connDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(QueryAdd, connDataBase);
MySqlDataReader myReader;
try
{
connDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Saved");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}发布于 2017-01-08 18:54:17
发布于 2017-01-08 19:10:14
我不知道MySQL和SQL是否是一回事,但是对于SQL,您可以使用带有ExecuteNonQuery()的Select Count (*)。如果该方法返回1,则存在重复项。如果不存在,则该记录不存在。
如果我错了,很抱歉。
https://stackoverflow.com/questions/41531860
复制相似问题