日期:2014-05-18 浏览次数:20914 次
/// <summary> /// 返回一个可供操作DataTable,支持Sql和OleDB /// </summary> /// <param name="strSQL">SQL语句</param> /// <param name="Connection">一个连接对象(OleDb或Sql类型)</param> /// <returns></returns> public static DataTable GetDataTable(string strSQL,IDbConnection Connection) { DataTable dt = new DataTable("BT"); DbDataAdapter da = null; if(Connection is SqlConnection) { da = new SqlDataAdapter(strSQL, Connection as SqlConnection); } else if(Connection is OleDbConnection) { da = new OleDbDataAdapter(strSQL, Connection as OleDbConnection); } else { throw new Exception("请传递一个OleDb或Sql类型的连接对象!"); } da.Fill(dt); return dt; }
------解决方案--------------------
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } }