【发布时间】:2015-02-19 17:42:24
【问题描述】:
int hid = 0;
int hid_auto = 0;
//Đổ dữ liệu
//HID
if (conn_class.OpenConnection() == true)
{
MySqlCommand hid_sql = new MySqlCommand("SELECT MAX(hid) FROM hotel", conn_class.connection);
hid = Convert.ToInt16(hid_sql.ExecuteScalar());
hid_auto = hid + 1;
conn_class.CloseConnection();
}
txt_Hid.Text = hid_auto.ToString();
//code that insert new record into database successfully
....... 更新:插入语句
if (general.TestEmail.IsEmail(txt_Email.Text) == true)
{
//Insert dữ liệu vào database
email = txt_Email.Text;
MySqlCommand them_hotel = new MySqlCommand("INSERT INTO quan_li.hotel (hid, name, star, address, province, phone, fax, email) VALUES (@hid, @name, @star, @address, @province, @phone, @fax, @email)");
them_hotel.CommandType = CommandType.Text;
them_hotel.Connection = conn_class.connection;
them_hotel.Parameters.AddWithValue("@hid", txt_Hid.Text);
them_hotel.Parameters.AddWithValue("@name", txt_Ten.Text);
them_hotel.Parameters.AddWithValue("@star", txt_Sao.Text);
them_hotel.Parameters.AddWithValue("@address", txt_DiaChi.Text);
them_hotel.Parameters.AddWithValue("@province", txt_Tinh.Text);
them_hotel.Parameters.AddWithValue("@phone", txt_DienThoai.Text);
them_hotel.Parameters.AddWithValue("@fax", txt_Fax.Text);
them_hotel.Parameters.AddWithValue("@email", txt_Email.Text);
conn_class.OpenConnection();
them_hotel.ExecuteNonQuery();
conn_class.CloseConnection();
thanh_cong = "Đã thêm khách sạn thành công";
}
我想找到隐藏列的 MAX() 值然后加 1 并发送到文本框。此事件在一个按钮中,但我第二次按下该按钮时,该值始终显示为第一次按下该按钮。
例如: 第一个:MAX() = 9 -> +1 -> 10 在文本框中。 -> 10 插入数据库 2nd ...n:文本框中的 10 和 10 插入数据库(2 行具有相同的值)。
如何将数据库中的 MAX() 值 +1?
感谢您的帮助。
P/s:对不起我的英语不好。
【问题讨论】:
-
这是一种方法吗?您发布的代码中不存在您的插入,所以它是否插入到酒店表中?
hid是自动递增的 ID 吗? -
你的插入逻辑一定有问题。在插入语句中隐藏是否正确?为什么不从中找出一个身份,而不是一开始就为最大值烦恼?
-
你确定第二次
conn_class.OpenConnection()是true吗? -
@Kritner 是的,一种方法。插入代码很长,但它可以正常工作,因为新记录已添加到数据库中。唯一的问题是隐藏列的值。 hid 是一个自动递增的 ID。我是一个初学者,我不知道如何处理自动增量ID,所以我考虑一下......
-
@DannyHai an
identity列(对于 sql server,可能对其他数据库有不同的术语)是一个自动递增的数字。如果表中没有记录,则插入一条记录,然后第一条记录的 ID 为 1,但不指定列的值,第二条记录为 2,依此类推。请注意,前面的陈述有一些注意事项,但这是基本思想。