sqltransaction什么意思SQL数据库基本操作、⽣成⽇志⽂件的⽅法
//数据库所在服务器IP
string servername = "192.168.2.137";
//数据库名字
string sqlname = "myTest";
//数据库账号
string usname= "myTest";
//数据库密码
string pwd = "123456";
//表名
string tablename="user";
/
/连接数据库语句
string strSql = "Server=" + servername + ";database=" + dbname + ";uid=" + usname + ";pwd=" + pwd + ";";
//建表⽅法
private static void creatTable(){
using (SqlConnection conn = new SqlConnection(mConnString)){
try{
if(conn.State== ConnectionState.Closed){
conn.Open();
}
StringBuilder sqlBuider = new StringBuilder("CREATE TABLE "+tablename+"(")
.Append("[id] [int] IDENTITY(1,1) NOT NULL,")
.Append("[UserName] [nvarchar](50) NULL,")
.Append("[UserPwd] [nvarchar](200) NULL")
SqlCommand cmd = new SqlCommand(sqlBuider.ToString(),conn);
cmd.ExecuteNonQuery();
}catch (Exception ex){
conn.Close();
}
}
}
// 执⾏修改、删除、添加的sql语句
private static Boolean update(string sql){
using(SqlConnection conn = new SqlConnection(mConnString)){
try{
if(conn.State== ConnectionState.Closed){
conn.Open();
}
SqlCommand com = new SqlCommand(sql,conn);
int result = com.ExecuteNonQuery();
conn.Close();
if (result > 0) return true;
}
catch(Exception ex){
conn.Close();
}
return false;
}
}
// 事务执⾏修改、删除、添加的sql语句
private static Boolean updateTran(List<string> sqlList,IsolationLevel leave){
if (sqlList.Count == 0) return false;
using(SqlConnection conn = new SqlConnection(mConnString)){
SqlTransaction tran = null;
try{
if(conn.State== ConnectionState.Closed){
conn.Open();
}
tran = conn.BeginTransaction(leave);
for (int index = 0; index < sqlList.Count; index++){
SqlCommand com = new SqlCommand(sqlList[index],conn);
SqlCommand com = new SqlCommand(sqlList[index],conn);
com.Transaction = tran;
int result = com.ExecuteNonQuery();
conn.Close();
if (result > 0) {
tran.Rollback();
return true;
}
}
tran.Commit();
return true;
}
catch(Exception ex){
if (tran != null){
tran.Rollback();
}
conn.Close();
}
return false;
}
}
//获取查询的记录集
public static  DataTable getTable(string sql){
using (SqlConnection conn = new SqlConnection(mConnString)){
try{
if(conn.State== ConnectionState.Closed){
conn.Open();
}
SqlDataAdapter adapter = new SqlDataAdapter(sql,conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
conn.Close();
return dt;
}catch (Exception ex){
conn.Close();
}
}
//添加⽇志⽂件
public static bool NoteLog(string line){
try{
string Fpath = System.Web.HttpContext.Current.Server.MapPath("~/bin/log");
if (!Directory.Exists(Fpath))
{
Directory.CreateDirectory(Fpath);
}
StreamWriter Note = new StreamWriter(Fpath + "/" + DateTime.Now.ToString("yyyyMMdd") + ".log", true, Encoding.Default);      Note.WriteLine(DateTime.Now.ToString() + "##" + line + "\r\n");
Note.Close();
}
catch (Exception ex){
}
return true;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。