Sql Table : stocks
Colomn Name | Data Type
------------------------------
Stock_no | nvarchar(15)
Quantity | int
Gem.Weight | float
Cost | decimal(18,2)
我的库存插入表单代码:
private void stocks_Click(object sender, EventArgs e)
{
try
{
cmd = new SqlCommand("INSERT INTO Stocks VALUES('" + txt_stock_no.Text + "', '"
+ txt_qty.Text + "','" + txt_gem_weight.Text + "', '" + txt_cost.Text + "')", conn);
MessageBox.Show("You've inserted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
我认为错误应该是我的'.text'有问题..我试着改变它,即使它不起作用。
txt_stock_no
应该只允许整数值。像这样的东西:
string commandText = "INSERT INTO Stocks VALUES(@stock_no, @txt_qty,@txt_gem_weight,@txt_cost)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("@stock_no", SqlDbType.Int);
command.Parameters["@stock_no"].Value = txt_stock_no.Text;
....
// do the same for other parameters
}
更新::
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.Add("@stock_no", SqlDbType.Int);
command.Parameters["@stock_no"].Value = txt_stock_no.Text;
....
// do the same for other parameters
用以下代码替换您的代码:
cmd = new SqlCommand("INSERT INTO Stocks VALUES('" + txt_stock_no.Text + "', "+ txt_qty.Text + "," + txt_gem_weight.Text + "," + txt_cost.Text + ")", conn);
int rowseffected=cmd.ExecuteNonQuery();
//rest of your code goes here...
但是,不建议这样做。这是查询易受SQL注入攻击。使用参数代替,您将不会再遇到这样的问题。