using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;sql
namespace DBTest
{
public class OpactionData
{
/// <summary>
/// 獲取數據庫鏈接地址,經過app.config文件來進行接收
/// </summary>
/// <returns>返回一個鏈接字符串信息</returns>
public static string GetConn()
{
string conn = ConfigurationManager.AppSettings["ConnectionString"];數據庫
/*app
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!-- 鏈接字符串是否加密-->
<add key="ConStringEncrypt" value="false"/>
<add key="ConnectionString" value="server=mis01;database=DB;uid=uid;pwd=Test123"/>
<!--<add key="ConnectionString" value="server=192.168.1.254;database=DB;uid=uid;pwd=ittest"/>-->
</appSettings>
</configuration>ide
*/ui
return conn;
}
/// <summary>
/// 執行一條sql語句,返回一個數據集
/// </summary>
/// <param name="sql">sql語句</param>
/// <returns>返回數據集</returns>
public static DataSet GetDataSet(string sql)
{
try
{
SqlConnection con = new SqlConnection(GetConn());
SqlDataAdapter ad = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}
catch
{
return null;
}
}
/// <summary>
/// 從數據庫中執行一條sql語句,並將執行結果返回到一個數據表中
/// </summary>
/// <param name="sql">sql語句</param>
/// <returns>返回一個數據表格信息</returns>
public static DataTable GetDateTable(string sql)
{
try
{
SqlConnection con = new SqlConnection(GetConn());
SqlDataAdapter ad = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds.Tables[0];
}
catch
{
return null;
}
}
/// <summary>
/// 執行一條sql語句並將操做結果,返回
/// </summary>
/// <param name="sql">sql語句</param>
/// <returns>返回影響記錄條數</returns>
public static int GetExecute(string sql)
{
SqlConnection con = new SqlConnection(GetConn());
try
{
con.Open();
SqlCommand com = new SqlCommand(sql, con);
int row = (int)com.ExecuteNonQuery();
con.Close();
return row;
}
catch
{
con.Close();
return 0;
}
}
/// <summary>
/// 執行一條sql語句,並將第一行第一列數據返回
/// </summary>
/// <param name="sql">執行一條sql語句</param>
/// <returns>返回一行一列的數據</returns>
public static object GetExecuteScalar(string sql)
{
SqlConnection con = new SqlConnection(GetConn());
try
{
con.Open();
SqlCommand com = new SqlCommand(sql, con);
object row = com.ExecuteScalar();
con.Close();
return row;
}
catch(Exception ex)
{
con.Close();
return null;
}
}
/// <summary>
/// 執行多條SQL語句,實現數據庫事務。
/// </summary>
/// <param name="SQLStringList">多條SQL語句</param>
public static int ExecuteSqlTran(List<String> SQLStringList)
{
using (SqlConnection conn = new SqlConnection(GetConn()))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
SqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
int count = 0;
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
count += cmd.ExecuteNonQuery();
}
}
tx.Commit();
return count;
}
catch
{
tx.Rollback();
return 0;
}
}
}
}
}
加密