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("数量不足,出库失败!");
}
}
}
如果把对数据库的操作写成方法直接调用,就回更好!虽然很简单,仍然希望对大家用所帮助!