步骤:
1 //数据库连接串 2 string conStr = "......" 3 //创建连接对象 4 SqlConnection connection = new SqlConnection(conStr); 5 //打开连接 6 connection.Open(); 7 8 //一、查询 9 //操作语句 10 string sql = "......" 11 //创建命令 12 SqlCommand command = new SqlCommand(sql, connection); 13 //添加参数 14 command.Parameters.Add(......); 15 //创建适配器 16 SqlDataAdapter adapter = new SqlDataAdapter(command); 17 //结果缓存 18 DataTable dataTable = new DataTable(); 19 //获取查询结果 20 adapter.Fill(dataTable); 21 22 //二、删除、更新、插入 23 //操作语句 24 string sql = "......" 25 //创建命令 26 SqlCommand command = new SqlCommand(); 27 //创建事务 28 SqlTransaction trans = connection.BeginTransaction(); 29 command.Connection = connection; 30 command.CommandText = sql; 31 command.Transaction = trans; 32 //添加参数 33 command.Parameters.Add(......); 34 try 35 { 36 //执行命令 37 rowsCountAffected = command.ExecuteNonQuery(); 38 //提交数据库事务 39 trans.Commit(); 40 } 41 catch 42 { 43 //回滚数据库事务 44 trans.Rollback(); 45 } 46 47 //关闭连接 48 connection.Close();