2.7 商品信息錄入界面功能設計
效果瀏覽:
錄入商品信息.gif

錄入商品信息.gif
主要功能:
庫管員為系統(tǒng)添加新的商品信息。
后臺數(shù)據(jù)庫結構表:

數(shù)據(jù)庫結構表.png
ADO.NET插入數(shù)據(jù)庫流程:
(1) 導入命名空間;
(2) 定義數(shù)據(jù)庫連接字符串,創(chuàng)建Connection對象;
(3) 打開連接;
(4) 利用Command對象的ExecuteNonQuery()方法執(zhí)行Insert語句;
(5) 通過ExecuteNonQuery()方法返回值判斷是否修改成功,并在界面上提示;
(6) 關閉連接。
迭代過程:
無外鍵:不用再load界面加代碼
有外鍵:在load界面加代碼
ComboBox數(shù)據(jù)綁定流程
private void Form1_Load(object sender, EventArgs e)
{
String connStr = ConfigurationManager.ConnectionStrings["SuperMarketSales"].ConnectionString;
SqlConnection sqlConn = new SqlConnection(connStr);
try
{
// 連接數(shù)據(jù)庫
sqlConn.Open();
// 綁定數(shù)據(jù)源
}
catch (Exception exp)
{
MessageBox.Show("訪問數(shù)據(jù)庫錯誤:" + 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)來標識數(shù)據(jù)庫的SUPPLIER表
adp.Fill(ds, "MySupplier");
// 指定ComboBox的數(shù)據(jù)源為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();
// 連接字符串,注意與實際環(huán)境保持一致
String connStr = ConfigurationManager.ConnectionStrings["SuperMarketSales"].ConnectionString;
SqlConnection sqlConn = new SqlConnection(connStr);
try
{
// 連接數(shù)據(jù)庫
sqlConn.Open();
}
catch (Exception exp)
{
MessageBox.Show(“訪問數(shù)據(jù)庫錯誤:” + exp.Message);
}
finally
{
sqlConn.Close();
}
連接數(shù)據(jù)庫
// 構造命令
String sqlStr = "insert into GOODS(ID, NAME, PRICE, SPEC, REMARK) values(@id, @name, @price, @spec, @remark)";
SqlCommand cmd = new SqlCommand(sqlStr, sqlConn);
// SQL字符串參數(shù)賦值
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));
// 將命令發(fā)送給數(shù)據(jù)庫
int res = cmd.ExecuteNonQuery();
// 根據(jù)返回值判斷是否插入成功
if (res != 0)
{
MessageBox.Show("商品信息錄入成功");
}
else
{
MessageBox.Show("商品信息錄入失敗");
}
錄入商品信息