CodeSmith实用技巧(十二):自动执行SQL脚本

CodeSmith中,如果生成的代码是SQL脚本,则可以在生成代码完成时自动执行生成的代码,也就是在生成的SQL脚本的同时在数据库中创建新的对象。

BaseTemplates.ScriptUtility对象提供ExecuteScript方法可以实现,如果想在生成代码完成后立即执行生成的脚本,可以很方便的通过重载OnPostRender来实现。<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

在使用之前,先添加对下列程序集的引用:

None.gif <% @ Assembly Name = " CodeSmith.BaseTemplates "   %>
None.gif
<% @ Import Namespace = " CodeSmith.BaseTemplates "   %>

看下面的这个例子:

None.gif protected   override   void  OnPostRender( string  result) 
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
// execute the output on the same database as the source table.
InBlock.gif
    CodeSmith.BaseTemplates.ScriptResult scriptResult = 
InBlock.gif     CodeSmith.BaseTemplates.ScriptUtility.ExecuteScript(
this.SourceTable.Database.ConnectionString, 
InBlock.gif     result, 
new System.Data.SqlClient.SqlInfoMessageEventHandler(cn_InfoMessage)); 
InBlock.gif    Trace.Write(scriptResult.ToString());
InBlock.gif    
base.OnPostRender(result);
ExpandedBlockEnd.gif}

None.gif
None.gif

在这个例子中SourceTable是一个类型为SchemaExplorer.TableSchema.的属性,使用的时候需要调整部分代码来获取数据库的连接以便在生成代码完成后执行脚本。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值