这是代码:
con.SqlQuery(" SELECT TOP 1000 [Name],[CompanyName],[Version] FROM[MicroinvestDatabasesCatalog].[dbo].[MicroinvestDatabases] ORDER BY NAME");
con.NonQueryEx();
以及连接和查询的类:
public SqlConnection conn;
public SqlCommand cmd;
public SqlDataAdapter da;
public DataTable dt;
public DataSet ds;
public void SqlDbConnect()
{
SqlConnection conn = new SqlConnection($"Data Source={server};User ID={user};Password={password};");
conn.Open();
}
public void SqlQuery(string queryText)
{
cmd = new SqlCommand(queryText, conn);
}
public DataTable QueryEx()
{
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
return dt;
}
public void NonQueryEx()
{
cmd.ExecuteNonQuery();
}
但cmd.ExecuteNonQuery();
有问题
有人可以帮助解决这个问题吗?
尝试不同的查询,但仍然相同......
答案 0 :(得分:3)
问题在于您的班级SqlDbConnect
。您有一个字段public SqlConnection conn
,但在构造函数中,您创建了一个类型为SqlConnection
的新变量,并将其打开。在构造函数中,您需要使用classes字段:
public SqlConnection conn;
public SqlCommand cmd;
public SqlDataAdapter da;
public DataTable dt;
public DataSet ds;
public void SqlDbConnect()
{
conn = new SqlConnection($"Data Source={server};User ID={user};Password={password};");
conn.Open();
}
public void SqlQuery(string queryText)
{
cmd = new SqlCommand(queryText, conn);
}
public DataTable QueryEx()
{
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
return dt;
}
public void NonQueryEx()
{
cmd.ExecuteNonQuery();
}
此外,如果您要选择数据,则无法使用ExecuteNonQuery
。相反,最好使用方法QueryEx()
,它会返回DataTable
:
con.SqlQuery("SELECT TOP 1000 [Name],[CompanyName],[Version] FROM[MicroinvestDatabasesCatalog].[dbo].[MicroinvestDatabases] ORDER BY NAME");
DataTable dt = con.QueryEx();