gpt4 book ai didi

创建新的 SqlDataAdapter 时出现 C# InvalidOperationException

转载 作者:行者123 更新时间:2023-11-30 21:42:14 29 4
gpt4 key购买 nike

我已经编写了一些代码来建立与 SQL Server 的连接,然后执行选择过程以从 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;
}
}

最佳答案

你应该:

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

关于创建新的 SqlDataAdapter 时出现 C# InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42708359/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com