1. 錄入界面運行效果:
運行效果展示.gif
2.畫面主要功能:
(1).首先查詢數據表GOODS中的商品信息铛绰,然后運行窗體程序罗心,使用數據庫中EMPLOYEE數據表中的庫管員數據ID進行登錄,登陸后打開錄入商品信息窗體蔗衡,按照指定格式錄入商品信息(每個商品條碼不同)竖共,錄入成功后再次在數據庫中查詢GOODS表中數據蝙叛。
表1.PNG
表2.PNG
表3.PNG
表4.PNG
3. ADO.NET插入數據庫流程:
1)導入命名空間;
2)定義數據庫連接字符串公给,創(chuàng)建Connection對象借帘;
3)打開連接;
4)利用Command對象的ExecuteNonQuery()方法執(zhí)行Insert語句淌铐;
5)通過ExecuteNonQuery()方法返回值反對是否修改成功肺然,并在界面上提示;
6)關閉連接腿准。
image.png
4. 功能迭代過程:
界面無外鍵時沒有供應商的選項际起,用GOODSINFO表時在這個數據庫表中是沒有外鍵的,通過添加供應商這一列的外鍵實現從數據庫GOODS表中直接用數據庫中SUPPLIER表中的數據吐葱。
5. Combobox數據綁定流程:
1)連接數據庫
2)綁定數據源
3)構造查詢命令
4)將該查詢過程綁定到DataAdapter
5)自定義一個表(MySupplier)來標識數據庫的SUPPLIER表
6)指定ComboBox的數據源為DataSet的MySupplier
6. 主要代碼:
1)Combobox數據源綁定:
{
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;
2. 增強功能的錄入商品信息界面
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
{
// 連接數據庫
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)";
(多了供應商字段,因此insert語句需要修改)
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));
// 將命令發(fā)送給數據庫
int res = cmd.ExecuteNonQuery();
// 根據返回值判斷是否插入成功
if (res != 0)
{
MessageBox.Show("商品信息錄入成功");
}
else
{
MessageBox.Show("商品信息錄入失敗");
}