现在的位置: 首页 > 综合 > 正文

在.net执行sql脚本的简单实现

2013年05月29日 ⁄ 综合 ⁄ 共 1594字 ⁄ 字号 评论关闭

看到csdn社区经常有人问在.net中假如执行sql脚本,下面是使用c#调用cmd来执行osql实现脚本的执行。

using system;

using system.data;

using system.collections;

using system.xml;

using system.io;

using system.text;

using system.diagnostics;

namespace zz

{

public class zzconsole

{

[stathread]

static void main(string[] args)

{

string sqlquery = "osql.exe /usa /p123 /s192.192.132.229 /dnorthwind /i yoursql.sql";

string strrst = execommand(sqlquery);

console.writeline(strrst);

console.readline();

}

public static string execommand(string commandtext)

{

process p = new process();

p.startinfo.filename = "cmd.exe";

p.startinfo.useshellexecute = false;

p.startinfo.redirectstandardinput = true;

p.startinfo.redirectstandardoutput = true;

p.startinfo.redirectstandarderror = true;

p.startinfo.createnowindow = true;

string stroutput = null;

try

{

p.start();

p.standardinput.writeline(commandtext);

p.standardinput.writeline("exit");

stroutput = p.standardoutput.readtoend();

p.waitforexit();

p.close();

}

catch(exception e)

{

stroutput = e.message;

}

return stroutput;

}

}

}

对于osql命名的参数如下:

=====================

用法: osql [-u login id] [-p password]

[-s server] [-h hostname] [-e trusted connection]

[-d use database name] [-l login timeout] [-t query timeout]

[-h headers] [-s colseparator] [-w columnwidth]

[-a packetsize] [-e echo input] [-i enable quoted identifiers]

[-l list servers] [-c cmdend] [-d odbc dsn name]

[-q "cmdline query"] [-q "cmdline query" and exit]

[-n remove numbering] [-m errorlevel]

[-r msgs to stderr] [-v severitylevel]

[-i inputfile] [-o outputfile]

[-p print statistics] [-b on error batch abort]

[-x[1] disable commands [and exit with warning]]

[-o use old isql behavior disables the following]

[-? show syntax summary]

具体参考

http://www.588188.com/netbook/sqlserver2000/coprompt/cp_osql_1wxl.htm

sql server 2000帮助文档

抱歉!评论已关闭.