使用C#在.MDF文件上运行SQL文件

时间:2013-08-08 09:59:39

标签: c# sql sql-server file-io

我在要运行.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;
    }
}

}

1 个答案:

答案 0 :(得分:3)

创建具有MDF扩展名的文件并不仅仅意味着这是一个有效的DB文件。它会给你一个错误,因为它不是一个有效的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();
    }
}