我如何运行sql服务器脚本与c#

本文关键字:服务器 sql 脚本 运行 何运行 | 更新日期: 2023-09-27 17:50:38

我写这个代码运行sql server脚本:

string sqlConnectionString = "Data Source=.;Initial Catalog=behzad;Integrated Security=True";
//string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("d:''behzadBULK.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Microsoft.SqlServer.Server server = new Microsoft.SqlServer.Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);


但是这一行:

Microsoft.SqlServer.Server server = new Microsoft.SqlServer.Server(new ServerConnection(conn));

 Are you missing reference?


应该在项目中添加什么参考?

我如何运行sql服务器脚本与c#

您的问题是缺少对汇编Microsoft.SqlServer.Server的引用,这就是为什么该错误弹出的原因。

您可以通过右键单击项目并单击add reference向该特定程序集的项目添加引用来解决此问题。这将打开一个窗口,显示所有可用的程序集,您可以从中选择此程序集并将其添加到项目中。

之后,确保在代码中为它添加了名称空间,这样就可以了。

尝试使用SQLclient连接而不是SqlServer

using System.Data;
using System.Data.SqlClient;

和一些像这样的代码

settings = System.Configuration.ConfigurationManager.ConnectionStrings["MyTweetConnection"];
ConnectionString = settings.ConnectionString;
SQLCon = new SqlConnection(ConnectionString);