【问题标题】:Problem with SqlConnection, ASP.net C#SqlConnection 的问题,ASP.net C#
【发布时间】:2011-05-17 07:08:03
【问题描述】:

我有以下 C# 代码:

public string TargetDate()
{
    SqlConnection con = 
        new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True");
    SqlCommand cmd = new SqlCommand("select * from Timer");
    con.Open(); 

    DataSet ds = new DataSet(cmd,con); 
    SqlDataAdapter da = new SqlDataAdapter(); 
    da.Fill(ds); 
    con.Close(); 
}

但我收到错误:new DataSet(cmd,con); ...

错误:CS1502:最好重载

的方法匹配
'System.Data.DataSet.DataSet(System.Runtime.Serialization.SerializationInfo,

System.Runtime.Serialization.StreamingContext)' 有一些无效的参数

可能是什么问题?

【问题讨论】:

标签: c# .net asp.net sql sql-server


【解决方案1】:

试试这个:

SqlConnection con = new SqlConnection
    ("Server=localhost;Database=Timer;Trusted_Connection=True");

SqlCommand cmd = new SqlCommand("select * from Timer", con);

con.Open();

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);

con.Close(); 

这样更好:

DataTable dataTable = new DataTable();
using(SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connection=True"))
using(SqlCommand command = connection.CreateCommand())
{
    command.CommandText = "select * from Timer";
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    dataTable.Load(reader);
}

【讨论】:

  • ExecuteReader 中使用CommandBehavior.CloseConnection 有什么不同吗?
  • 另外:修正错字 Trusted_Connection=True 而不是 Trusted_Connectopn=True
  • +1 using....... 块!甚至更好:不要使用SELECT *,而是明确指定您真正需要的列...
【解决方案2】:

DataSet 的构造函数有误。试试这个

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(con);

【讨论】:

  • 是否有接受SqlCommand和SqlConnection的SqlDataAdapter构造函数?
  • @Alex:啊,我明白了,我将字符串“selectCommandText”与 SqlCommand 对象混淆了。你是对的。
  • 哇 3 upvotes 不一致的东西!我相信您应该澄清 cmd 是 string 而不是 command 对象
【解决方案3】:

看来你把构造函数弄混了:

尝试以下方法:

DataSet ds = new DataSet(); 

SqlDataAdapter da = new SqlDataAdapter(con); 

希望有帮助

【讨论】:

  • 是否有接受SqlCommand和SqlConnection的SqlDataAdapter构造函数?
猜你喜欢
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多