C#创建SqlServer数据库

C#创建SqlServer数据库代码如下所示:

using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str;
            SqlConnection myConn = new SqlConnection("Server=localhost;Initial Catalog=testDb;User ID=sa;Password=123456");  //数据库连接字符串

            str = "CREATE DATABASE MyDatabase ON PRIMARY " +  //数据库名称
                  "(NAME = MyDatabase_Data, " +   //逻辑名称
                  "FILENAME = 'D:\\MyDatabaseData.mdf', " +  //文件存储路径
                  "SIZE = 2MB, MAXSIZE = 1000MB, FILEGROWTH = 10MB) " +   //SIZE=文件初容量,MAXSIZE=文件最大容量,FILEGROWTH=文件增量
                  "LOG ON (NAME = MyDatabase_Log, " +  // 数据库日志文件
                  "FILENAME = 'D:\\MyDatabaseLog.ldf', " +  //日志文件路径
                  "SIZE = 1MB, " +  //日志文件初始容量
                  "MAXSIZE = 100MB, " +  //日志文件最大容量
                  "FILEGROWTH = 10%)";  //日志文件增量

            SqlCommand myCommand = new SqlCommand(str, myConn);
            try
            {
                myConn.Open();
                myCommand.ExecuteNonQuery();
                MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                if (myConn.State == ConnectionState.Open)
                {
                    myConn.Close();
                }
            }
        }
    }
}

参考:https://support.microsoft.com/zh-cn/help/307283/how-to-create-a-sql-server-database-programmatically-by-using-ado-net

你可能感兴趣的:(c#学习笔记)