I used SQLDMO in C # to create a new database, encountered a problem: The database file save path problem
First select a SQL Server on the local network (DATASRV), and then create a new database on it, one of the parameters in the creation process: PhysicalName is the specified database file (. MDF), assuming the designation is d:/temp/test. MDF is saved under the d:/temp/of the server (DATASRV).
To specify that there is no problem with the string, you can create a new database file in the server's specified folder (even if it is not shared), but I want to use a SaveFileDialog box to allow the user to choose a path to store. The problem is (assuming that the username and password for administrator privileges on the server are known) I can only see and access the folders that are shared on the server, but using such a pathname physicalname parameter is not acceptable, for example: Server Datasrv shares a folder called share in D disk. The PhysicalName parameter can only accept "d:/share/test." MDF "Such a path does not accept"//datasrv/share/test. MDF "Such a path.
There seem to be two solutions: a Let the SaveFileDialog box access the "My Computer" on the server (like accessing native) B) and get its absolute path on the server through the shared folder
The relevant code is as follows:
SQLDMO. Application Sqlapp = new SQLDMO. ApplicationClass ();
SQLDMO. SQL Server SRV = new SQLDMO. Sqlserverclass ();
Srv. Connect (srvname, "sa", "");
if (srvname!= "local")
Sfdnewdb.initialdirectory = @ "//" + srvname;
if (sfdnewdb.showdialog () = = DialogResult.Cancel)
{
Srv. Close ();
Sqlapp.quit ();
Return
}
DBPath = Sfdnewdb.filename;
dbname = dbpath.substring (Dbpath.lastindexof ("") +1,dbpath.length-dbpath.lastindexof ("//")-5);
BOOL Dbexist = false;
foreach (SQLDMO. Database db in SRV. Databases)
{
if (db. Name = = dbname)
{
Dbexist = true;
}
}
if (dbexist)
{
stas.items["Ssldb"]. Text = "This data inventory name already exists Please choose a different name";
Srv. Close ();
Sqlapp.quit ();
Return
}
Else
stas.items["Ssldb"]. Text = "Creating database ...";
SQLDMO. Database NDB = new SQLDMO. Database ();
SQLDMO. DBFile ndbfile = new SQLDMO. DBFile ();
SQLDMO. LogFile nlogfile = new SQLDMO. LogFile ();
Ndb.name = dbname;
Ndbfile.name = dbname + "file";
Ndbfile.physicalname = @dbPath;
Ndbfile.primaryfile = true;
Ndbfile.filegrowthtype = 0;
Ndbfile.filegrowth = 1;
NDB.FileGroups.Item ("PRIMARY"). Dbfiles.add (Ndbfile);
Nlogfile.name = dbname + "Log";
Nlogfile.physicalname = @dbPath. Substring (0,dbpath.length-3) + "LDF";
NDB.TRANSACTIONLOG.LOGFILES.ADD (Nlogfile);
Srv. Databases.add (NDB);
The program here complains:
The physical file name '//datasrv/share/test. MDF ' My is incorrect
Srv. Close ();
Sqlapp.quit ();
My temporary solution:
String dbpath = srv. Registry.sqldataroot + "//data//" + dbname;
Save the file to the Data folder in the SQL Server installation folder