应用事物

 public partial class Form1 : Form
    {
       
        SqlConnection Linkstr()
        {
            SqlConnection sql=new SqlConnection();
            sql.ConnectionString = "server=.;database=Store;uid=sa;pwd=liulu123";
            return sql;
        }
        DataTable Search(string str)
        {
            DataSet ds = new DataSet();
            SqlConnection conn = Linkstr();
            conn.Open();

            SqlCommand comm = new SqlCommand();
            comm.CommandText = str;
            comm.Connection = conn;

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = comm;
            da.Fill(ds);
            conn.Close();

            return ds.Tables[0];
        }
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string str1 = "select * from Goods";
            DataTable mydt = Search(str1);
            comboBox1.DataSource = mydt;
            comboBox1.DisplayMember = "name";
        }

        private void button1_Click(object sender, EventArgs e)
        {
          
            SqlConnection conn = Linkstr();
            SqlTransaction tran=null;
            conn.Open();

            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
          
           try
           {
               tran = conn.BeginTransaction();
               comm.Transaction = tran;
               comm.CommandText = "insert into Outstore(name,count,trantime) values('" + comboBox1.Text + "'," + textBox1.Text + ",'" + DateTime.Now + "')";
               int t = comm.ExecuteNonQuery();
               comm.CommandText = "update Goods set number=number-" + textBox1.Text + " where name='" + comboBox1.Text + "'";
               int i = comm.ExecuteNonQuery();
               if (i == 1 && t == 1)
               {
                   tran.Commit();
                   conn.Close();
                   MessageBox.Show("提交事务,出库成功!");
               }
           }
           
          catch
           {
                tran.Rollback();
                conn.Close();
                MessageBox.Show("数量不足,出库失败!");
            }

        }
    }

如果把对数据库的操作写成方法直接调用,就回更好!虽然很简单,仍然希望对大家用所帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值