2.7 商品信息录入界面功能设计
效果浏览:
录入商品信息.gif
主要功能:
库管员为系统添加新的商品信息。
后台数据库结构表:

ADO.NET插入数据库流程:
(1) 导入命名空间;
(2) 定义数据库连接字符串,创建Connection对象;
(3) 打开连接;
(4) 利用Command对象的ExecuteNonQuery()方法执行Insert语句;
(5) 通过ExecuteNonQuery()方法返回值判断是否修改成功,并在界面上提示;
(6) 关闭连接。
迭代过程:
无外键:不用再load界面加代码
有外键:在load界面加代码
ComboBox数据绑定流程
private void Form1_Load(object sender, EventArgs e)
{
String connStr = ConfigurationManager.ConnectionStrings["SuperMarketSales"].ConnectionString;
SqlConnection sqlConn = new SqlConnection(connStr);
try
{
// 连接数据库
sqlConn.Open();
// 绑定数据源
}
catch (Exception exp)
{
MessageBox.Show("访问数据库错误:" + exp.Message);
}
finally
{
sqlConn.Close();
}
}
// 构造查询命令
String sqlStr = "select * from SUPPLIER order by CODE";
SqlCommand cmd = new SqlCommand(sqlStr, sqlConn);
// 将该查询过程绑定到DataAdapter
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
// 将DataSet和DataAdapter绑定
DataSet ds = new DataSet();
// 自定义一个表(MySupplier)来标识数据库的SUPPLIER表
adp.Fill(ds, "MySupplier");
// 指定ComboBox的数据源为DataSet的MySupplier表
this.comboBox1.DataSource = ds.Tables["MySupplier"];
this.comboBox1.DisplayMember = "NAME";
this.comboBox1.ValueMember = "CODE";
this.comboBox1.SelectedIndex = 0;
重要代码:
String id = this.tb_Id.Text.Trim();
String name = this.tb_Name.Text.Trim();
float price = float.Parse(this.tb_Price.Text.Trim());
String spec = this.tb_Spec.Text.Trim();
String remark = this.tb_Remark.Text.Trim();
// 连接字符串,注意与实际环境保持一致
String connStr = ConfigurationManager.ConnectionStrings["SuperMarketSales"].ConnectionString;
SqlConnection sqlConn = new SqlConnection(connStr);
try
{
// 连接数据库
sqlConn.Open();
}
catch (Exception exp)
{
MessageBox.Show(“访问数据库错误:” + exp.Message);
}
finally
{
sqlConn.Close();
}
连接数据库
// 构造命令
String sqlStr = "insert into GOODS(ID, NAME, PRICE, SPEC, REMARK) values(@id, @name, @price, @spec, @remark)";
SqlCommand cmd = new SqlCommand(sqlStr, sqlConn);
// SQL字符串参数赋值
cmd.Parameters.Add(new SqlParameter("@id", id));
cmd.Parameters.Add(new SqlParameter("@name", name));
cmd.Parameters.Add(new SqlParameter("@price", price));
cmd.Parameters.Add(new SqlParameter("@spec", spec));
cmd.Parameters.Add(new SqlParameter("@remark", remark));
// 将命令发送给数据库
int res = cmd.ExecuteNonQuery();
// 根据返回值判断是否插入成功
if (res != 0)
{
MessageBox.Show("商品信息录入成功");
}
else
{
MessageBox.Show("商品信息录入失败");
}
录入商品信息
网友评论