if (this.txb_Add_MedicineName.Text.Trim() == “”) //若用户号文本框为空;
{
MessageBox.Show(“药名不能为空!”); //给出错误提示;
this.txb_Add_MedicineName.Focus(); //用户号文本框获得焦点;
return; //返回;
}
if (this.txb_Add_MedicineNo.Text.Trim() == “”) //若密码文本框为空;
{
MessageBox.Show(“药品编号不能为空!”); //给出错误提示;
this.txb_Add_MedicineNo.Focus(); //密码文本框获得焦点;
return; //返回;
}
//if (this.txb_Add_Date.Text.Trim() == “”) //若密码文本框为空;
//{
// MessageBox.Show(“入库日期不能为空!”); //给出错误提示;
// this.txb_Add_Date.Focus(); //密码文本框获得焦点;
// return; //返回;
//}
SqlConnection sqlConnection = new SqlConnection(); //声明并实例化SQL连接;
sqlConnection.ConnectionString =
“Server=(local);Database=ChineseMedicine;Integrated Security=sspi”; //在字符串变量中,描述连接字符串所需的服务器地址、数据库名称、集成安全性(即是否使用Windows验证);
SqlCommand sqlCommand = sqlConnection.CreateCommand(); //调用SQL连接的方法CreateCommand来创建SQL命令;该命令将绑定SQL连接;
sqlCommand.CommandText = //指定SQL命令的命令文本;
“UPDATE tb_ChineseMedicine”
+ " SET Medicine=@Medicine"
+ " WHERE MedicineNo=@No;";
sqlCommand.Parameters.AddWithValue("@Name", this.txb_Name.Text.Trim());
sqlCommand.CommandText =
“INSERT tb_ChineseMedicine (MedicineName,MedicineNo,InTime) VALUES(@MedicineName,@MedicineNo,@InTime);”; //指定SQL命令的命令文本;命令文本包含参数;
sqlCommand.Parameters.AddWithValue("@MedicineName", this.txb_Add_MedicineName.Text.Trim()); //向SQL命令的参数集合添加参数的名称、值;
sqlCommand.Parameters.AddWithValue("@MedicineNo", this.txb_Add_MedicineNo.Text.Trim());
sqlCommand.Parameters.AddWithValue("@InTime", Convert.ToDateTime (this.txb_Add_Date.Text.Trim()));
sqlCommand.Parameters["@MedicineNo"].SqlDbType = SqlDbType.VarChar;
sqlCommand.Parameters["@MedicineName"].SqlDbType = SqlDbType.VarChar;
sqlConnection.Open();
//打开SQL连接;
int rowAffected = 0; //声明整型变量,用于保存受影响行数;
try
{
rowAffected = sqlCommand.ExecuteNonQuery(); //调用SQL命令的方法ExecuteNonQuery来执行命令,向数据库写入数据,并返回受影响行数;
}
catch (SqlException sqlEx) //捕捉SQL异常;
{
if (sqlEx.Number == 2627) //若SQL异常编号为2627,则违反主键/唯一约束,即插入重复值;
{
MessageBox.Show("您添加的药瓶编号已存在,请重新输入!"); //给出准确通俗的错误提示;
}
}
sqlConnection.Close(); //关闭SQL连接;
if (rowAffected == 1) //若成功写入1行记录;
{
MessageBox.Show("添加成功。"); //显示正确提示;
}
else //否则;
{
MessageBox.Show("添加失败!"); //显示错误提示;
}
添加功能的纠错和总结:在做的过程中添加总是失败,要注意文本框的文本内容和其他数据类型的转换
依然存在的问题:怎么使用Update语句将int类型的数据更新。经过自己的摸索发现因为数据库中的int类型数据时Null,没法进行相加,所以总是失败。