@MiPakTeh , Based on my test, you could try the following code to check if the database exists.
public static bool CheckDatabaseExists(string dataBase)
{
string conStr = @"connstr";
string cmdText = String.Format("SELECT * FROM sys.databases where Name='{0}'", dataBase);
bool isExist = false;
using (SqlConnection connection = new SqlConnection(conStr))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(cmdText, connection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
isExist = reader.HasRows;
}
}
connection.Close();
}
return isExist;
}
Please use the following sql text to check if the database exists.
SELECT * FROM sys.databases where Name='test'
Update for CreateDatabase problem:
public void CreateDatabase(string dataBase)
{
SqlConnection connection = new SqlConnection(@"str");
using (connection)
{
connection.Open();
string sql = string.Format(@"CREATE DATABASE [{0}]ON PRIMARY (NAME={0}, FILENAME = '{1}\{0}.mdf')
LOG ON (NAME=txt, FILENAME = '{1}\{0}.ldf')", dataBase,@"D:\DB");
SqlCommand command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
}
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Jack