0

我在要运行 .sql 文件的特定位置有一个 .MDF 文件。我正在使用以下代码,但它做得不是很好。

它总是给我错误,无法连接到服务器并且无法读取物理文件!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System;
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

namespace Testing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    private void btnCreateDatabase_Click(object sender, EventArgs e)
    {
        string dir = GetParentPath() + "\\Database";  // folder location
        if (!Directory.Exists(dir))
            Directory.CreateDirectory(dir);

        File.Create(GetParentPath() + "\\Database\\test_db.mdf");

        try
        {
            string sqlConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + GetParentPath() + "\\Database\\test_db.mdf" + ";Integrated Security=SSPI;User Instance=true";

            FileInfo file = new FileInfo(GetParentPath() + "\\test_db.MDF.sql");

            string script = file.OpenText().ReadToEnd();

            SqlConnection conn = new SqlConnection(sqlConnectionString);

            Server server = new Server(new ServerConnection(conn));

            server.ConnectionContext.ExecuteNonQuery(script);
            file.OpenText().Close();
            MessageBox.Show("DataBase is Created Successfully", "Create a Database", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.ToString(), "Create a Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        finally
        {
            //if (myConn.State == ConnectionState.Open)
            //{
            //    myConn.Close();
            //}
        }

    }
    private string GetParentPath()
    {
        string DbPath = System.AppDomain.CurrentDomain.BaseDirectory;
        int Posn;
        for (int Counter = 0; Counter != 2; Counter++)
        {
            Posn = DbPath.LastIndexOf("\\");
            DbPath = DbPath.Substring(0, Posn);
        }
        return DbPath;
    }
}

}

4

1 回答 1

3

创建一个带有 MDF 扩展名的文件并不仅仅意味着这是一个有效的 DB 文件。它给你一个错误,因为它不是一个有效的数据库文件。

如果要创建数据库,请使用此代码。当然,根据需要更改参数。

String str;
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");

str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"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();
    }
}
于 2013-08-08T10:04:43.437 回答