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