如何插入而不将列表框中的值更改为数据库 我有3个列表框和数据库中的表,代码......
private void Order()
{
using (SqlConnection connection = new SqlConnection(connectionString1))
{
String query = "INSERT INTO Tbl_order (OrderName,Quantity,Price,Serves_way,Date) VALUES (@OrderName,@Quantity, @Price,'"+servers+"','" + time1.ToString(format1)+"' )";
connection.Open();
for (int i = 0; i < lst_OrderName.Items.Count; i++)
{
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.Add("OrderName", SqlDbType.NVarChar).Value = lst_OrderName.GetItemText(lst_OrderName.GetSelected(i));
command.Parameters.Add("Quantity", SqlDbType.Int).Value = Convert.ToInt32(lst_QTY.GetSelected(i));
command.Parameters.Add("Price", SqlDbType.Money).Value = Convert.ToDouble(lst_Price2.GetSelected(i));
/* command.Parameters.AddWithValue("@OrderName", lst_OrderName.GetItemText(lst_OrderName.Items));
command.Parameters.AddWithValue("@Quantity", lst_QTY.GetItemText(lst_QTY.Items));
command.Parameters.AddWithValue("@Price", lst_Price2.GetItemText(lst_Price2.Items));*/
command.ExecuteNonQuery();
}
}
}
}
所以3个列表框就像这样,带有值字符串,int和double
以及数据库中的插入值
如您所见,它们与列表框值的值不同
如何将列表框中的相同值插入数据库?
答案 0 :(得分:1)
您可以使用准备好的查询。您可以通过添加参数及其数据类型来准备查询,列的长度是可选的。然后拨打Prepare()
。之后,按索引或列名称将数据分配给参数,最后调用ExecuteNonQuery
private void Order()
{
using (SqlConnection connection = new SqlConnection(connectionString1))
{
String query = "INSERT INTO Tbl_order (OrderName,Quantity,Price,Serves_way,Date) VALUES (@OrderName,@Quantity, @Price,'"+servers+"','" + time1.ToString(format1)+"' )";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
// Add the length of this text column as third parameter...
command.Parameters.Add("OrderName", SqlDbType.NVarChar);
command.Parameters.Add("Quantity", SqlDbType.Int);
command.Parameters.Add("Price", SqlDbType.Money);
command.Prepare();
for (int i = 0; i < lst_OrderName.Items.Count; i++)
{
// Dont know if the .ToString() calls are necessary...
command.Parameters[0].Value = lst_OrderName.GetItemText(lst_OrderName.Items[i].ToString());
command.Parameters[1].Value = Convert.ToInt32(lst_QTY.Items[i].ToString());
command.Parameters[2].Value = Convert.ToDouble(lst_Price2.Items[i].ToString());
command.ExecuteNonQuery();
}
}
}
}
编辑: 更新了答案,以便从每个ListBox中正确获取项目(正如Steve已经提到的那样)