【问题标题】:C# InvalidOperationException when creating a new SqlDataAdapter创建新的 SqlDataAdapter 时出现 C# InvalidOperationException
【发布时间】:2017-03-10 01:06:29
【问题描述】:

我已经编写了一些代码来建立与 SQL Server 的连接,然后执行 select 过程以从我在 SQL Server 中的数据表中获取所有数据,但是它在声明一个新的 SqlDataAdapter 的命令中抛出了 InvalidOperationException,请帮助我修复此错误。

public class dBConnect
{
    //create SQLconnection variable
    private SqlConnection con;
    //create default constructor that passing a string to con
    public dBConnect()
    {
        try
        {
            con = new SqlConnection(@"Server=Trump\SQLEXPRESS;
        Database=Demo;User Id=sa;Password = stevejobs;");
        }
        catch(Exception exCon)
        {
            Console.WriteLine("Unable to connect to database: {0}", exCon);
        }
    }
    //create Select method to Pour the data into the DataTable
    public DataTable SelectAll(string procName, SqlParameter[] para = null)
    {
        //create a DataTable to store Data from DB
        DataTable dt = new DataTable();
        //create SQLCommand
        SqlCommand cmd = new SqlCommand(procName, con);
        //declare that cmdType is sp
        cmd.CommandType = CommandType.StoredProcedure;
        //input parameter of cmd
        if (para != null)
            cmd.Parameters.AddRange(para);
        //create dataAdapter object

        //InvalidOperationException was thrown at here
        SqlDataAdapter da = new SqlDataAdapter(cmd);

        //declare that cmd is select command of da 
        da.SelectCommand = cmd;
        //use try/catch/finally to establish a connection
        try
        {
            con.Open();
            da.Fill(dt);
        }
        catch(Exception sqlEx)
        {
            Console.WriteLine(@":Unable to establish a connection: {0}", sqlEx);
        }
        finally
        {
            con.Close();
            con.Dispose();
        }
        return dt;
    }
}

}

【问题讨论】:

  • 我认为这意味着 SQL 命令本身存在问题,因此您应该先检查这些问题。此外,您可能应该将 SqlConnection、SqlCommand 和 SqlDataAdapter 包装在 using 语句中。
  • 这里有点奇怪。第一次通过登录表单连接到数据库时,一切正常。但是当我关闭主表单并返回登录表单并尝试再次登录时,会出现错误对话框。这个对话框的内容是“connectionstring property has not been initialized”。

标签: c# sql-server


【解决方案1】:

你应该:

cmd.CommandText = "your Stored Procedure here.";
cmd.CommandType = CommandType.StoredProcedure;
//input parameter of cmd
if (para != null)
cmd.Parameters.AddRange(para);
//create dataAdapter object

把你的con.Open();放在上面

看看这个步骤

 DataTable dt = new DataTable();
 using (SqlConnection con = new SqlConnection(connectionString))
 {
     con.Open();
      using (SqlCommand cmd = con.CreateCommand())
      {
       //sample stored procedure with parameter:
       // "exec yourstoredProcedureName '" + param1+ "','" + param2+ "'";
       cmd.CommandText = "Your Stored Procedure Here";
       cmd.CommandType =CommandType.StoredProcedure;
       using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
        {
            adp.Fill(dt);
             return dt;
        }
      }
  }

【讨论】:

  • 小心你的“para”,因为它是一个数组..只是一个“Heads Up”。
【解决方案2】:

在这里稍微清理一下您的代码:

public DataTable SelectAll(string procName, SqlParameter[] para = null)
        {
            DataTable dt = new DataTable();
            try
            {
                using (SqlConnection con = new SqlConnection(connString))
                {
                    con.Open();

                    using (SqlCommand cmd = new SqlCommand(procName, con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        if (para != null)
                            cmd.Parameters.AddRange(para);

                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {

                            da.Fill(dt);
                        }
                    }
                }
            }
            catch (Exception sqlEx)
            {
                Console.WriteLine(@":Unable to establish a connection: {0}", sqlEx);
            }

            return dt;

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    相关资源
    最近更新 更多