1. 程式人生 > >NHibernate直接執行SQL進行插入

NHibernate直接執行SQL進行插入

有時候,需要用NHibernate直接執行SQL進行資料insert或update。

怎麼寫呢?簡單一點的,可以直接拼湊出來的SQL,這樣寫:

using NHibernate;

StringBuilder sb = new StringBuilder($@"insert into {tablename}(id,report_Id) values({id},{reportid})");
ISQLQuery query = Session.CreateSQLQuery(sb.ToString());
return query.ExecuteUpdate() > 0;

如果怕注入攻擊,帶引數,醬紫寫:

StringBuilder strSQL = new StringBuilder("insert into SDE.HaiDiDianLanGuanDaoP (ObjectID,StartName,UseMode,PermitGUID,IsRight,UseModeName,Sat_Marker,shape) ");
strSQL.Append(" values ");
strSQL.AppendFormat("((select sde.version_user_ddl.next_row_id('SDE', (SELECT registration_id SEQ FROM sde.table_registry WHERE owner = 'SDE' and table_name ='{0}' )) OBJECTID from dual)"
, "HaiDiDianLanGuanDaoP".ToUpper()); strSQL.Append(",:StartName,:UseMode,:PermitGUID,:IsRight,:UseModeName,:Sat_Marker,SDE.ST_TransForm(SDE.ST_Buffer(SDE.ST_TransForm(decode(to_char(substr(:shape,1,2)),'',null,sde.st_geometry(:shape, 0)), 102028), 10), 4326))"); ISQLQuery query = Session.CreateSQLQuery
(strSQL.ToString()); query.SetParameter("StartName", daoL.STARTNAME); query.SetParameter("UseMode", daoL.USEMODE); query.SetParameter("PermitGUID", daoL.PERMITGUID); query.SetParameter("IsRight", daoL.ISRIGHT); query.SetParameter("UseModeName", daoL.USEMODENAME); query.SetParameter("Sat_Marker", daoL.SAT_MARKER); query.SetParameter("shape", daoL.SHAPE); return query.ExecuteUpdate() > 0;