我有这样的代码:
private bool CheckDatabase(string databaseName, bool bRet)
{
string connString = "Server=localhost\\SQLEXPRESS;Integrated Security=SSPI;database=master";
string cmdText = "select * from master.dbo.sysdatabases where name=\'" + databaseName + "\'";
using (SqlConnection sqlConnection = new SqlConnection(connString))
{
sqlConnection.Open();
using (SqlCommand sqlCmd = new SqlCommand(cmdText, sqlConnection))
{
int nRet = sqlCmd.ExecuteNonQuery();
// regMessage.Text = nRet.ToString();
if (nRet <= 0)
{
bRet = false;
}
else
{
bRet = true;
}
}
}
return bRet;
}
然而
NRET
结果始终为-1,好像数据库不存在(确实如此)。 这是问题因为数据库是空的吗? 或者,如果创建了数据库,它是否应返回&gt; 0,即使它是空的? 顺便说一句,字符串databaseName是正确的。
编辑&gt; 编辑: 我也得到了#34; CREATE DATABASE @ database&#34; ssql命令:
&#39; @ userDatabase&#39;
附近的语法不正确
代码就像这样:
var connString = "Server=localhost\\SQLEXPRESS;Integrated Security = SSPI; database = master";
string cmdText = "CREATE DATABASE @userDatabase";
using (var sqlConnection = new SqlConnection(connString))
{
using (var sqlCmd = new SqlCommand(cmdText, sqlConnection))
{
sqlCmd.Parameters.Add("@userDatabase", System.Data.SqlDbType.NVarChar).Value = databaseName;=
sqlConnection.Open();
sqlCmd.ExecuteNonQuery();
}
}
答案 0 :(得分:4)
Select count(*)
代替Select *
。ExecuteScalar
代替ExecuteNonQuery
// No point of passing a bool if all you do is return it...
private bool CheckDatabase(string databaseName)
{
// You know it's a string, use var
var connString = "Server=localhost\\SQLEXPRESS;Integrated Security=SSPI;database=master";
// Note: It's better to take the connection string from the config file.
var cmdText = "select count(*) from master.dbo.sysdatabases where name=@database";
using (var sqlConnection = new SqlConnection(connString))
{
using (var sqlCmd = new SqlCommand(cmdText, sqlConnection))
{
// Use parameters to protect against Sql Injection
sqlCmd.Parameters.Add("@database", System.Data.SqlDbType.NVarChar).Value = databaseName;
// Open the connection as late as possible
sqlConnection.Open();
// count(*) will always return an int, so it's safe to use Convert.ToInt32
return Convert.ToInt32( sqlCmd.ExecuteScalar()) == 1;
}
}
}
答案 1 :(得分:3)
不,您不能使用ExecuteNonQuery从SELECT语句返回内容,您到该MSDN论坛的链接包含错误的答案(正如您已经尝试过的那样)
MSDN docs解释说,ExecuteNonQuery仅返回sql语句受UPDATE / INSERT / DELETE查询影响的行数。要计算受SELECT影响的行数,它应该检索结果,还需要做更多的工作。这可能不是表现明智的。
所以你可以将你的功能改为
private bool CheckDatabase(string databaseName)
{
string connString = "Server=localhost\\SQLEXPRESS;Integrated Security=SSPI;database=master";
string cmdText = @"if Exists(select 1 from master.dbo.sysdatabases where name=@db)
select 1 else select 0";
using (SqlConnection sqlConnection = new SqlConnection(connString))
{
sqlConnection.Open();
using (SqlCommand sqlCmd = new SqlCommand(cmdText, sqlConnection))
{
sqlCmd.Parameters.Add("@db", SqlDbType.NVarChar).Value = databaseName;
int nRet = Convert.ToInt32(sqlCmd.ExecuteScalar());
return (nRet > 0);
}
}
}
我改变了什么:
答案 2 :(得分:0)
如果知道数据库文件在哪里,则可以使用File.Exists()
:
if (File.Exists(DatabaseFile))
{
//DoSomething
}