首页 > 开发 > .Net > 正文

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

2020-02-03 15:58:50
字体:
来源:转载
供稿:网友
在.net执行sql脚本的简单实现

郑佐2004-12-25

看到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帮助文档



上面程序是我以前在csdn回答问题时写的,由于最近比较忙,所以偷懒了。对于本文有什么好的建议或意见请留言。zhzuo(秋枫)


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表