[英]Querying master.sys.databases view in SQL Server 2008 R2 from c# is not working
I'm using the code below to find if a database exists but the ExecuteNonQuery
always returns -1. 我正在使用下面的代码来查找数据库是否存在,但是
ExecuteNonQuery
始终返回-1。
I've seen the master.sys.databases
view and it has the database POS
我看过
master.sys.databases
视图,它具有数据库POS
SqlConnection tmpConn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
sqlCheckDBQuery = "SELECT * FROM master.sys.databases where name = \'aspnetdb\'";
using (tmpConn)
{
try
{
tmpConn.Open();
tmpConn.ChangeDatabase("master");
}
catch (Exception)
{
MessageBox.Show("SQLServer Express Database is either not installed or not running!", "Database Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
using (SqlCommand sqlCmd = new SqlCommand(sqlCheckDBQuery, tmpConn))
{
int exists = sqlCmd.ExecuteNonQuery();
if (exists <= 0)
databaseExists = false;
else
databaseExists = true;
}
}
in this particular instance you can use a scalar query instead of a data reader. 在这种特定情况下,您可以使用标量查询代替数据读取器。
sqlCheckDBQuery = "SELECT count(1) FROM master.sys.databases where name = 'aspnetdb'";
var count = (int)sqlCmd.ExecuteScalar();
databaseExists = count > 1;
You should use ExecuteScalar()
and change the query to run a COUNT(*)
. 您应该使用
ExecuteScalar()
并更改查询以运行COUNT(*)
。
ExecuteScalar
will bring back the rows affected. ExecuteScalar
将带回受影响的行。
ExecuteNonQuery()
will bring back -1 for SELECT
's. ExecuteNonQuery()
将为SELECT
返回-1。
ExecuteNonQuery()
is the wrong method to use. ExecuteNonQuery()
是使用错误的方法。 Use ExecuteReader()
instead: eg: 使用
ExecuteReader()
代替:例如:
var reader = command.ExecuteReader();
if (reader.Read())
....
sqlCheckDBQuery = "SELECT * FROM master.sys.databases where name = \'aspnetdb\'";
Why are you using backslashes here? 为什么在这里使用反斜杠? The name of the database is
aspnetdb
so this should be: 数据库的名称是
aspnetdb
因此应为:
sqlCheckDBQuery = "SELECT * FROM master.sys.databases where name = 'aspnetdb'";
Also as has been mentioned in other answers you cannot use ExecuteNonQuery()
here since that will return always -1 for select statements. 另外,正如其他答案中提到的那样,您不能在此处使用
ExecuteNonQuery()
,因为对于选择语句,该值将始终返回-1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.