c#检测是否存在数据库(SQL SERVER)

时间:2022-04-07 16:16:52
private static bool CheckDatabaseExists( string databaseName)
{ {
string sqlCreateDBQuery;
bool result = false; try
{
SqlConnection tmpConn = new SqlConnection(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=Example;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;"); sqlCreateDBQuery = string.Format("SELECT database_id from sys.databases WHERE Name = '{0}'", databaseName); using (tmpConn)
{
using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
{
tmpConn.Open(); object resultObj = sqlCmd.ExecuteScalar(); int databaseID = ; if (resultObj != null)
{
int.TryParse(resultObj.ToString(), out databaseID);
} tmpConn.Close(); result = (databaseID > );
}
}
}
catch (Exception ex)
{
result = false;
} return result;
}
}