
在配置文件中配置連接字符串
- 在“解決方案資源管理器”中的“引用”條目上右鍵添加 System.Configuration
-
修改項目的 App.config 文件,添加如下彩色內(nèi)容
image.png
3)在需要連接數(shù)據(jù)庫的窗口代碼中添加 using System.Configuration;
4)按如下語法引用連接字符串
image.png
2. 設計并制作商品信息錄入界面

(1) 設置父窗體
將要作為“父窗體” 的窗體的IsMdiContainer屬性設置為true
通過屬性窗口設計即可。

(2)設置子窗體
將要作為“子窗體” 的窗體的MdiParent屬性屬性指定為“父窗體”。
只有通過代碼,在實例化“子窗體”后設置,如下:
FormChild formChild1 = new FormChild(); // 創(chuàng)建子窗體對象
formChild1.MdiParent = this; // 設置子窗體的父窗體為當前窗體
formChild1.Show(); // 在MDI中顯示子窗體
3. 編碼實現(xiàn)商品信息存入數(shù)據(jù)庫表
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();// 構(gòu)造命令
String sqlStr = "insert into GOODSINFO(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("商品信息錄入失敗");
}
}
catch (Exception exp)
{
MessageBox.Show("訪問數(shù)據(jù)庫錯誤:" + exp.Message);
}
finally
{
sqlConn.Close();
}

