从 sql express 获取数据库名称

Get the name of db from sql express

我已使用此连接字符串将我的 sql 数据库自动连接到 sql express:

Data Source=.\SQLEXPRESS; AttachDBFileName=|DataDirectory|\DB\MyDBName.mdf; User ID=sa;Password=MyPass;Persist Security Info=True

一切正常,但问题是当我想从我的 db.The sql express 获取备份时,在附加数据库时更改了数据库的名称,因此在备份查询中我收到此错误:

Database 'MyDBName' does not exist.Make sure that the name is entered correctly. BACKUP DATABASE is terminating abnormally.

我的备份查询是:

BACKUP DATABASE [MyDBName] TO DISK=N'" + filePath + "' WITH NOFORMAT, INIT, SKIP, NOREWIND, NOUNLOAD, STATS = 10;

有什么方法可以从 sql 快速获取我的数据库的当前名称 自动附加到 sql 时设置我的数据库的名称快递?

首先执行以下查询并获取数据库名称

SELECT DB_NAME() AS DataBaseName

 SqlCommand cmd = new SqlCommand("SELECT DB_NAME() AS dbName",your_connection);
 string name = cmd.executeScalar().ToString();
 //now do what ever you want to with db name