用于SqlServer数据库的SqlServerHelper.cs类,及其调用例子(二)

2014-11-24 12:18:13 · 作者: · 浏览: 1
public static bool UpdateData(out string sError, string sSQL, bool bUseTransaction=false)
{
int iResult = 0;
sError = string.Empty;

if (!bUseTransaction)
{
try
{
SqlConnection conn = new SqlConnection(_ConnString);
if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = sSQL;
iResult = comm.ExecuteNonQuery();
}
catch (Exception ex)
{
sError = ex.Message;
iResult = -1;
}
}
else // 使用事务
{
SqlTransaction trans = null;
try
{
SqlConnection conn = new SqlConnection(_ConnString);
if (conn.State != ConnectionState.Open)
conn.Open();
trans = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sSQL;
cmd.Transaction = trans;
iResult = cmd.ExecuteNonQuery();
trans.Commit();
}
catch (Exception ex)
{
sError = ex.Message;
iResult = -1;
trans.Rollback();
}
}

return iResult > 0;
}

}
}

调用方法:

一,先设置数据库连接的信息

//SqlServerHelper.ConnString = @"server=电脑名 或 电脑IP;database=数据库名;uid=数据库登录名;password=数据库登录密码";

SqlServerHelper.Conn_Config_Str_Name = @"ConnString"; // ConnString的信息在 App.Config里设置

//SqlServerHelper.Conn_Server = @"电脑名 或 电脑IP";
//SqlServerHelper.Conn_DBName = "数据库名";
//SqlServerHelper.Conn_Uid = "数据库登录名";
//SqlServerHelper.Conn_Pwd = "数据库登录密码";

二, App.Config

< xml version="1.0" encoding="utf-8" >




三, 读取 datatable / dataset 数据

private void InitGrid()
{

string sSQL = "select * from test";

string sError = string.Empty;

DataTable dt = SqlServerHelper.GetDataTable(out sError, sSQL);

//DataSet dt = SqlServerHelper.GetDataSet(out sError, sSQL);

dataGridView1.DataSource = dt;

if (!string.IsNullOrEmpty(sError))
Common.DisplayMsg(this.Text, sError);

}

四,插入,修改,删除 数据 (都调用SqlServerHelper.UpdateData方法)

// 插入

string sError = string.Empty;
int iMaxID = SqlServerHelper.GetMaxID(out sError, "id", "test") + 1;
string sSql = "insert into test select " + iMaxID + ",'name" + iMaxID + "','remark" + iMaxID + "'";
sError = string.Empty;
bool bResult = SqlServerHelper.UpdateData(out sError, sSql, true);
if (bResult)
Common.DisplayMsg(this.Text, "插入成功");
else
Common.DisplayMsg(this.Text, sError);

InitGrid();

// 修改