美文网首页
2018-05-25

2018-05-25

作者: Korona | 来源:发表于2018-05-25 17:25 被阅读0次

2.8商品信息录入界面功能介绍

1.录入过程

录入.gif

1.1主要功能

录入商品信息

1.2数据表结构

数据表结构.PNG

2.ADO.NET插入数据库流程

图片4.png

具体步骤:

  1. 导入命名空间;
  2. 定义数据库连接字符串,运用Connection对象建立与数据库连接;
  3. 打开连接;
  4. 利用Command对象的ExecuteNoQuery()方法执行Insert语句;
  5. 通过ExecuteNoQuery()方法返回值判断是否修改成功,并在界面上提示;
  6. 关闭连接。

3.画面功能迭代过程

图片1.png
图片2.png

在第二版本中,录入界面新添加了供应商选项,使用ComboBox控件,可下拉选择对应的供应商。

4.ComboBox数据绑定流程

ComboBox数据源绑定的三个要素:
1) 设置DataSource属性
2) 设置DisplayMember属性
3) 设置ValueManager属性

将该查询过程绑定到DataAdapter
将DataSet和DataAdapter绑定
自定义一个表(MySupplier)来标识数据库的SUPPLIER表
指定ComboBox的数据源为DataSet的MySupplier表

5.重要代码

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();
// 构造命令
String sqlStr = "insert into GOODSINFO(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("商品信息录入失败");
}


}
catch (Exception exp)
{
    MessageBox.Show(“访问数据库错误:” + exp.Message);
}
finally
{
    sqlConn.Close();
}

以上代码是为实现商品录入

private void Form1_Load(object sender, EventArgs e)
{
    String connStr = ConfigurationManager.ConnectionStrings["SuperMarketSales"].ConnectionString;
    SqlConnection sqlConn = new SqlConnection(connStr);
    try
    {
        // 连接数据库
        sqlConn.Open();

// 构造查询命令
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;

        // 绑定数据源
    }
    catch (Exception exp)
    {
        MessageBox.Show("访问数据库错误:" + exp.Message);
    }
    finally
    {
        sqlConn.Close();
    }
}

以上代码实现ComboBox数据源绑定。

相关文章

网友评论

      本文标题:2018-05-25

      本文链接:https://www.haomeiwen.com/subject/kblujftx.html