【发布时间】:2014-04-21 02:17:27
【问题描述】:
private void txtBarcode_KeyUp(object sender, KeyEventArgs e)
{
try
{
string connString = "Server=192.168.1.100;Database=product;Uid=newuser;Pwd=password";
MySqlConnection conn = new MySqlConnection(connString);
//cmd = conn.CreateCommand();
//cmd.CommandText = "Select * From tblindividualproduct";
if (e.KeyCode == Keys.Enter)
{
if (txtBarcode.Text == "")
{
MessageBox.Show("Please Fill the correct ProductID");
}
else
{
if (HasRecord("tblindividualproduct.ProductID", connString) == false)
{
string sql = "Select Iproduct.ProductId, prodInfo.Name,Iproduct.UpdatedPrice From product.tblproductinformation AS prodInfo INNER JOIN product.tblindividualproduct AS Iproduct ON prodInfo.Code = Iproduct.Code where Iproduct.ProductID = @idText";
using (var adapt = new MySqlDataAdapter(sql, conn))
using (var cmd = new MySqlCommandBuilder(adapt)) //Not sure what you need this for unless you are going to update the database later.
{
adapt.SelectCommand.Parameters.AddWithValue("@idText", txtBarcode.Text);
adapt.Fill(dt);
dgItems.ReadOnly = true;
dgItems.DataSource = dt;
}
}
}
}
}
catch (MySqlException ex)
{
// output the error to see what's going on
MessageBox.Show(ex.Message);
}
}
static public bool HasRecord(string ProductID, string connString)
{
//add try catches where required
bool foundRecord = true;
Int32 numRecords = 0;
string sql =
"Select count(Iproduct.ProductId, prodInfo.Name,Iproduct.UpdatedPrice) From product.tblproductinformation AS prodInfo INNER JOIN product.tblindividualproduct AS Iproduct ON prodInfo.Code = Iproduct.Code where Iproduct.ProductID = @idText";
using (MySqlConnection conn = new MySqlConnection(connString))
{
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.Add("@idText", SqlDbType.VarChar);
cmd.Parameters["@idText"].Value = ProductID;
try
{
conn.Open();
numRecords = (Int32)cmd.ExecuteScalar();
if (numRecords == 0) foundRecord = false;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return foundRecord;
}
我使用此代码在我的数据集中添加项目,您能帮我了解如何检查条目,如果它在数据集中有重复条目,则不会接受它?
编辑:我更新了我的代码,向您展示我目前的工作。
【问题讨论】:
-
重复条目是什么意思?您的意思是查询中的相同行?
-
我的意思是如果我输入的产品 ID 为 1,我会再次输入。它不会接受它,因为它会在我的数据表中有重复的条目。
标签: c# mysql database datatable