我想在c#中执行sql脚本我该怎么做呢。 [英] I want to execute sql script in c# how can i do this.
问题描述
您好,
我想通过C#在sql server中执行sql脚本。在这里我想通过app.config获取sql脚本路径。
我该怎么做
谢谢
Hello,
I want to execute sql script in sql server through C#. here i want to get sql script path through app.config.
how can i do this
thanks
推荐答案
第一个链接将为您提供从web.config获取服务器和数据库信息的解决方案。
如何从webconfig中的connectionstring中检索databaseName和serverName? />
以下链接将为您提供在C#中运行.sql脚本的解决方案
在C#中运行.sql脚本文件
运行C#中的.sql脚本文件
你也可以使用 sqlcmd Utility 。
Microsoft SQL Server 2005功能包
Following first link will provide you the solution to get server and database information from web.config.
How to retrieve the databaseName and the serverName from the connectionstring in the webconfig?
And following links will provide you a solution to run a .sql script in C#
Run a .sql script file in C#
Run a .sql script files in C#
You can also use sqlcmd Utility.
Feature Pack for Microsoft SQL Server 2005
将文件中的脚本加载到字符串中,并将其设置为cmdText到SqlCommand对象。
然后调用相应的命令方法:ExecuteScalar,ExecuteReader或ExecuteNonQuery
Load the script from the file into a string, and set it as the cmdText to an SqlCommand object.
Then call the appropriate command method: ExecuteScalar, ExecuteReader, or ExecuteNonQuery
你可以使用SMO(Sql server)管理对象)由C#。
使用以下库执行此操作:
you can use SMO (Sql server Management Object) by C#.
using the following library to execute this :
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
示例代码如下:
FileInfo file = new FileInfo(ScriptFile.sql);
string script = file.OpenText() .ReadToEnd();
SqlConnection conn = GetSqlConnection(); //创建连接
服务器服务器=新服务器(新的ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
Sample Code like this :
FileInfo file = new FileInfo("ScriptFile.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = GetSqlConnection(); // create connection
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
这篇关于我想在c#中执行sql脚本我该怎么做呢。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!