我创建了一个C#应用程序来查询和插入产品数据库。但是我在这里有一个小小的疑问,如果有人可以帮助我,我马上谢谢您。
以下是:
这是直到现在的我的代码:
private void btn_save_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=product.accdb");
OleDbCommand check_sn = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([sn] = @sn)", con);
OleDbCommand check_reference = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([reference] = @ref)", con);
OleDbCommand check_number = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([number] = @num)", con);
con.Open();
check_reference.Parameters.AddWithValue("@ref", textBox_ref.Text);
check_sn.Parameters.AddWithValue("@sn", textBox_sn.Text);
check_number.Parameters.AddWithValue("@num", textBox_num.Text);
int refExist = (int)check_reference.ExecuteScalar();
int SNExist = (int)check_sn.ExecuteScalar();
int numExist = (int)check_number.ExecuteScalar();
if (refExist > 0)
{
MessageBox.Show("A product with this reference already exists....!");
}
else if (SNExist> 0)
{
MessageBox.Show("A product with this sale number already exists....!");
}
else if (numExist > 0)
{
MessageBox.Show("A product with this archive number already exists....!");
}
else
{
try
{
String reference = textBox_ref.Text.ToString();
String sn = textBox_ov.Text.ToString();
String cod_client = textBox_cod.Text.ToString();
String client = textBox_cliente.Text.ToString();
String qtd = textBox_qtd.Text.ToString();
String number = textBox_num.Text.ToString(); //This will be the incremented number
String my_querry = "INSERT INTO product(reference,sn,cod_client,client,qtd,number)VALUES('" + reference + "','" + sn + "','" + cod_client + "','" + client + "','" + qtd + "','" + number + "')";
OleDbCommand cmd = new OleDbCommand(my_querry, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfully...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
con.Close();
}
cleanTextBoxes(this.Controls);
}
}
private void search_btn_Click(object sender, EventArgs e)
{
Form search = new Form_search();
search.Show();
this.Hide();
}
}
}
谢谢
答案 0 :(得分:0)
好吧,我已经尝试过并且可以工作,但是现在我要如何将该值+1递增?
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Aneis_Calibre.accdb");
con.Open();
OleDbDataReader myReader = null;
OleDbCommand number = new OleDbCommand("SELECT TOP 1 [number] FROM product Order by [number] desc", con);
myReader = number.ExecuteReader();
while (myReader.Read())
{
textBox_num.Text = (myReader["number"].ToString());
}
con.Close();
答案 1 :(得分:0)
在查询中,您需要按照以下步骤进行操作。
INSERT ...
OUTPUT inserted.identity_column
VALUES (...)
这将返回带有id值的行。 SQL中的标识列将始终为您自动增加。这将减轻您获取最后一条记录并执行操作的方式:
int.TryParse(reader["..."]?.ToString(), out int id);
textbox.Text = id++;
通过使用标量或阅读器,尽管我建议使用标量,如果您返回带有修改后的SQL查询的单列,则会得到确切的新插入的ID。