问题
I've created an Amazon AWS RDS instance running MS SQL. I've successfully been able to programmatically create a database in C# using:
SqlConnection myConn = new SqlConnection("Data Source=<public-ip-name>;Persist Security Info=True;User ID=<userid>;PWD=<pwd>;");
myConn.Open();
string str = "CREATE DATABASE contacts";
SqlCommand cmd = new SqlCommand(str, myConn);
cmd.ExecuteNonQuery();
However, I haven't been able to make a more complex connection string work:
str = "CREATE DATABASE contacts ON PRIMARY " +
"(NAME = Contacts_Data, " +
@"FILENAME = 'c:\contacts.mdf', " +
"SIZE = 4MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = Contacts_Log, " +
@"FILENAME = 'c:\contacts.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
The error (5) seems to complain that C:\ can't be written to. Perhaps it doesn't exist? If I omit FILENAME, an error complains that I omitted it. What is the correct value for FILENAME? It appears that FILENAME must specify an existing file path.
回答1:
I've coded jtseng's answer in C#
static string GetDBPath(SqlConnection myConn, string db = "master")
{
string sqlstr = "USE " + db + "; EXEC sp_helpfile";
SqlCommand command = new SqlCommand(sqlstr, myConn);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow);
reader.Read();
string filename = reader["filename"].ToString();
string directory = System.IO.Path.GetDirectoryName(filename);
return directory;
}
called via:
SqlConnection myConn = new SqlConnection("Data Source=<public ip>;Persist Security Info=True;User ID=<userid>;PWD=<pwd>;");
myConn.Open();
string dbPath = GetDBPath(myConn); // default db is master
回答2:
To find out which directory you can create databases in:
- Create a database DB1 the simple way.
Find out where the database files are located:
USE DB1 GO EXEC sp_helpfile GO
Create a database with the files in that directory.
来源:https://stackoverflow.com/questions/17410121/amazon-aws-rds-how-to-programmatically-create-a-ms-sql-database-in-c