public class DB
{
SqlConnection con = null;
SqlCommand cmd = new SqlCommend;
private bool flag ;
public DB ()
{ //此处添加构造函数逻辑
con = new SqlConnection ( " Data Source = . ; Initial Catalog = vote ; User ID = sa ; pwd = yang ; " ) ;
}
public SqlConnection getCon () //打开链接
{
if ( con.State == ConnectionState.Closed)
{
con.Open();
}
return con ;
}
public void clear () //关闭连接
{
if ( con.State == ConnectionState.Open )
{
con.Close ();
}
}
public string executeGetReturn ( string strSql )
{ //执行查询语句返回结果的第一行第一列
cmd.Connection = getCon ();
cmd.CommandText = strSql ;
string result = cmd.ExecteScalar().ToString();
clear();
return result;
}
public DataSet getDs ( string strSql , string tableName )
{ // 得到一个数据集
SqlDataAdapt sda = new SqlDataAdapt ( strSql , getCon () ) ;
DataSet ds = new DataSet () ;
sda.Fill ( ds , " tableName " ) ;
clear () ;
return ds;
}
public bool executeTransation ( string [] strSql )
{
con = getCon () ;
cmd.Connection = con ;
SqlTranscation myTranscation = con.BeginTransaction () ;
try
{
for ( int i=0 ; i<strSql.Length ; i++)
{
cmd.Transaction = myTransaction ;
cmd.CommandText = strSql [ i ];
cmd.ExecuteNonQuery () ;
}
myTransaction.Commit () ;
flag = true ;
}
catch ( Exception )
{
myTransaction.Rollback () ;
flag = flase ;
}
return flag ;
}
}