22,207
社区成员
发帖
与我相关
我的任务
分享
public SqlConnection GetCon()
{
try
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "参数配置.xml");
if (File.Exists(configFile))
{
XmlOperator xmlOperator = new XmlOperator(configFile);
int size = xmlOperator.GetXmlReader().Length;
string[] getDataBaseInfo = new string[size];
for (int i = 0; i < size; i++)
{
getDataBaseInfo[i] = xmlOperator.GetXmlReader()[i];
}
string G_Str_ConnectionString = "Server=" + getDataBaseInfo[0];
G_Str_ConnectionString += ";user id=" + getDataBaseInfo[1];
G_Str_ConnectionString += ";password=" + getDataBaseInfo[2];
G_Str_ConnectionString += ";initial catalog=" + getDataBaseInfo[3] + ";Connect Timeout=20";
G_Con = new SqlConnection(G_Str_ConnectionString);
G_Con.Open();
}
else
{
MessageBox.Show("不存在配置文件,请添加!");
Application.Exit();
}
}
catch (Exception ex)
{
MessageBox.Show("数据库打开失败,错误原因:" + ex.Message.ToString());
}
return G_Con;
}
/// <summary>
/// 执行SQL语句
/// </summary>
/// <param name="cmdtxt">要执行的SQL语句</param>
/// <returns></returns>
public bool GetExecute(string cmdtxt)
{
try
{
G_Com = new SqlCommand(cmdtxt, GetCon());
if (G_Com.ExecuteNonQuery() > 0)
{
int count = G_Com.ExecuteNonQuery();
MessageBox.Show(count.ToString());
return true;
}
else
return false;
}
catch (Exception ex)
{
MessageBox.Show("GetExecute函数错误:" + ex.Message.ToString());
return false;
}
finally
{
if (GetCon().State == ConnectionState.Open)
{
GetCon().Close();
G_Com.Dispose();
}
}
}
#endregion
#region 返回数据
/// <summary>
/// 返回数据集类型
/// </summary>
/// <param name="cmdtxt">需要查询的SQL语句</param>
/// <returns></returns>
public DataSet GetDs(string cmdtxt, string table)
{
try
{
G_Da = new SqlDataAdapter(cmdtxt, GetCon());
G_Ds = new DataSet();
G_Da.Fill(G_Ds, table);
return G_Ds;
}
catch (Exception ex)
{
MessageBox.Show("错误:" + ex.Message.ToString());
return null;
}
finally
{
if (GetCon().State == ConnectionState.Open)
{
GetCon().Close();
this.Dispose();
}
}
}
/// <summary>
/// 返回SqlDataReader类型数据
/// </summary>
/// <param name="cmdtxt">要执行的SQL语句</param>
/// <returns></returns>
public SqlDataReader GetReader(string cmdtxt)
{
G_Com = new SqlCommand(cmdtxt, GetCon()); //声明SqlCommand对象
SqlDataReader P_Dr;
try
{
P_Dr = G_Com.ExecuteReader(CommandBehavior.CloseConnection);
return P_Dr;
}
catch (Exception ex)
{
MessageBox.Show("错误:" + ex.Message.ToString());
return null;
}
}
public DataSet GetDs(string cmdtxt, string table)
{
try
{
SqlConnection conn = GetCon();
G_Da = new SqlDataAdapter(cmdtxt, conn);
G_Ds = new DataSet();
G_Da.Fill(G_Ds, table);
return G_Ds;
}
catch (Exception ex)
{
MessageBox.Show("错误:" + ex.Message.ToString());
return null;
}
finally
{
//释放资源
if (G_Da != null)
{
G_Da.Dispose();
}
if (conn.State == ConnectionState.Open)
{
conn.Close();
this.Dispose();
}
}
}
finally
{
if (GetCon().State == ConnectionState.Open)
{
GetCon().Close();
G_Com.Dispose();
}
}