【发布时间】: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