public static bool executescala(string sqlstr)
    {
        int count = 0;
        SqlCommand cmd = new SqlCommand(sqlstr);
        using (SqlConnection con = new SqlConnection(dbconnString))
        {
            createConnection(con);     //打开连接
            try
            {
                count = Convert.ToInt32(cmd.ExecuteScalar());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                closecon(con);
            }
            if (count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }请问这部分代码可有什么不妥的地方吗??

解决方案 »

  1.   

    sqlcommand也要加一个using, 在sqlconnection下面
      

  2.   

    createConnection(con);没有多大意义,直接CON。OPEN()就可以了!
    另外closecon(con); 画蛇添足,因为前面用的是USING,用完就释放了!
      

  3.   

    这样的代码不要自己去写.应为你根本就没有什么严谨的测试.
    DataAccess的代码,满大街都是.
    刚开始,可以去用一下:SqlHelper,它的源代码很多地方都能找到.
      

  4.   

    cmd.Connection = con;
    SqlCommand的Connection对象没有赋值.
      

  5.   

    用得着这样专门写个方法?createConnection(con);    //打开连接    closecon(con); 
      

  6.   

    下面的写法也许会更好    public static bool executescala(string sqlstr)
        {
            int count = 0;
            try
            {
                using (SqlConnection con = new SqlConnection(dbconnString))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand(sqlstr,con);
                    count = Convert.ToInt32(cmd.ExecuteScalar());
                }
            }
            catch (Exception ex)
            {        }        return count > 0;
        }