日期:2014-05-18  浏览次数:20914 次

C#编写一个数据库查询的公共函数?怎么调用?
请问,怎么用C#编写一个数据库查询的公共函数?怎么调用?

------解决方案--------------------
public static void Show()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ST_StuManager;Integrated Security=True");

SqlDataAdapter sda = new SqlDataAdapter("select * from ST_student", con);
DataSet ds=new DataSet();

sda.Fill(ds,"stuTable");

foreach (DataRow item in ds.Tables["stuTable"].Rows)
{
Console.WriteLine(item[0]+"\t"+item[1]);
}


}
static void Main()
{
Show();
}

是不是这样啊
------解决方案--------------------
C# code

/// <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;
}
}
}
}
C# code

/// <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;
            }
        }