用c#怎么执行一个sql脚本(如:abc.sql) 谢谢 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 public static void ExecuteSqlInFile( string connectionString, string pathToScriptFile ) { try { StreamReader _reader = null; string sql = ""; if( false == System.IO.File.Exists( pathToScriptFile )) { throw new Exception("文件 " + pathToScriptFile + " 未找到"); } Stream stream = System.IO.File.OpenRead( pathToScriptFile ); _reader = new StreamReader( stream ); SqlConnection connection = new SqlConnection( connectionString ); SqlCommand command = new SqlCommand(); connection.Open(); command.Connection = connection; command.CommandType = System.Data.CommandType.Text; while( null != (sql = ReadNextStatementFromStream( _reader ) )) { command.CommandText = sql; command.ExecuteNonQuery(); } _reader.Close(); } catch(Exception ex) { Trace.WriteLine("在文件: " + pathToScriptFile + " 中产生异常。"); Trace.WriteLine(ex.Message); MessageBox.Show("处理文件错误", "Error"); } } private static string ReadNextStatementFromStream( StreamReader _reader ) { StringBuilder sb = new StringBuilder(); string lineOfText; while(true) { lineOfText = _reader.ReadLine(); if( lineOfText == null ) { if( sb.Length > 0 ) { return sb.ToString(); } else { return null; } } if( lineOfText.TrimEnd().ToUpper() == "GO" ) { break; } sb.AppendFormat("{0}\r\n", lineOfText ); } return sb.ToString(); } 用存储过程更好吧?可以这样,filestream 可以读入文件内容,放入string里,传给sqlcommand,就可以执行了,和普通sql一样. 建立一个cmd,用osql就可以了吧 写过一篇文章,http://blog.csdn.net/zhzuo/archive/2004/12/25/229006.aspx 读出SQL文本,有GO的地方就执行,没有的行就添加到一个字符串函数里 datagridview怎样显示隐藏掉的行 请教一个很简单的程序代码 c# 中英文版问题 DataSet 作用域的菜问题 基类的实例和派生类的实例可以强制转换吗? 请教“实例变量”和“全局变量”的区别和联系! C#画一个圆,我怎么实现不了呢 誰有關于java和C#之間的比較的文章啊﹐救急啊 很简单的问题,请帮帮初学的小弟我,谢谢!! 访问ACCESS 数据库问题 C#中如何实现vb中的InputBox()? 专家们,一个关于继承的问题,帮忙.
{
try
{
StreamReader _reader = null; string sql = ""; if( false == System.IO.File.Exists( pathToScriptFile ))
{
throw new Exception("文件 " + pathToScriptFile + " 未找到");
}
Stream stream = System.IO.File.OpenRead( pathToScriptFile );
_reader = new StreamReader( stream ); SqlConnection connection = new SqlConnection( connectionString );
SqlCommand command = new SqlCommand(); connection.Open();
command.Connection = connection;
command.CommandType = System.Data.CommandType.Text; while( null != (sql = ReadNextStatementFromStream( _reader ) ))
{
command.CommandText = sql; command.ExecuteNonQuery();
} _reader.Close();
}
catch(Exception ex)
{
Trace.WriteLine("在文件: " + pathToScriptFile + " 中产生异常。");
Trace.WriteLine(ex.Message);
MessageBox.Show("处理文件错误", "Error");
}
} private static string ReadNextStatementFromStream( StreamReader _reader )
{ StringBuilder sb = new StringBuilder(); string lineOfText;
while(true)
{
lineOfText = _reader.ReadLine(); if( lineOfText == null )
{
if( sb.Length > 0 )
{
return sb.ToString();
}
else
{
return null;
}
} if( lineOfText.TrimEnd().ToUpper() == "GO" )
{
break;
}
sb.AppendFormat("{0}\r\n", lineOfText );
} return sb.ToString();
}
http://blog.csdn.net/zhzuo/archive/2004/12/25/229006.aspx