Amazon AWS RDS - How to Programmatically Create a MS SQL Database in C#?

倾然丶 夕夏残阳落幕 提交于 2019-12-10 12:29:34

问题


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:

  1. Create a database DB1 the simple way.
  2. Find out where the database files are located:

    USE DB1 GO EXEC sp_helpfile GO

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!