通用数据库操作方法(SQL语句篇)

来源:互联网 发布:链家端口费是什么意思 编辑:程序博客网 时间:2024/06/14 10:53

   #region 查询 SQL语句返回Dataset 类型
    /// <summary>
    /// 传入SQL语句和表别名,查询数据库,取出结果集放入DataSet中
    /// </summary>
    /// <param name="sql">sql语句</param>
    /// <param name="tmpTable">数据库表名</param>
    /// <returns>DataSet表</returns>
    public DataSet getDataSet(string sql, string tmpTable)
    {
        ds = null;
        try
        {
            con = new SqlConnection(conStr);
            cmd = new SqlCommand(sql, con);
            da = new SqlDataAdapter(cmd);
            ds = new DataSet();
            con.Open();
            da.Fill(ds, tmpTable);
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message + "無法連接數據庫");
        }
        finally
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
        }
        return ds;
    }
    #endregion

    #region 查詢SQL語句,返囬Datatable 類型
    /// <summary>
    /// 传入SQL语句,查询数据库,取出结果集放入DataTable中
    /// </summary>
    /// <param name="sql">sql语句</param>
    /// <returns>DataTable表</returns>
    public DataTable getDataTable(string sql)
    {
        dt = null;
        try
        {
            con = new SqlConnection(conStr);
            cmd = new SqlCommand(sql, con);
            da = new SqlDataAdapter(cmd);
            dt = new DataTable();
            con.Open();
            da.Fill(dt);
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message + "無法連接數據庫");
        }
        finally
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
        }
        return dt;
    }
    #endregion

    #region 查询 返回String 型
    /// <summary>
    /// 传入SQL语句,查询数据库,当结果只有1行1列时,取出结果集放入string中
    /// </summary>
    /// <param name="sql">sql语句</param>
    /// <returns>string字符串</returns>
    public string getString(string sql)
    {
         string str="";
        dt = null;
        try
        {
            con = new SqlConnection(conStr);
            cmd = new SqlCommand(sql, con);
            da = new SqlDataAdapter(cmd);
            dt = new DataTable();
            con.Open();
            da.Fill(dt);
           str  = dt.Rows[0][0].ToString();
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message + "無法連接數據庫");
        }
        finally
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
        }
      
        return str;
    }
    #endregion 

原创粉丝点击