Sometimes, you may need to perform SQL statements directly, stored procedures, etc., but NHibernate does not provide a method that allows us to perform SQL statements, but you can implement it through some indirect methods. 1. The IDRIVER Interface Idriver interface is the drive of the data accessed. For different data providers (SqlClient, OLEDB, etc.), there is a different drive, and the SQLClient corresponds to SQLClientDriver, and the OLEDB corresponds to OLEDBDriver. The iDriver interface is used to get the connection object, the command object, and format the command text. 2. Get the database connection object To perform SQL, you must get the IDBConnection object, which can be obtained by the session factory. It should be noted that the iSessionFactory interface does not provide an operation related to the connection object, which is defined by the iSessionFactoryImplementor interface. ISessionFactoryImplementor inherits from iSessionFactory, and the session factory for the session factory implements these two interfaces. To obtain connection object codes as follows: ISessionFactoryImplementor factory = (ISessionFactoryImplementor) cfg.BuildSessionFactory (); IDbConnection conn = factory.OpenConnection (); OpenConnection method provides connections made by ConnectionProvider IDbConnection objects, connected through the provider creates IDbConnection Driver object. 3. Get the IDBCommand object inside NHibernate, data operation is done by the IDBCommand object, using the Command object to prevent injection attacks and handle some special characters. Under the code of the idbcommand object: idbcommand cmd = factory.ConnectionProvider.driver.createCommand (); maybe someone will ask, directly new sqlcommand () can not be (if you have words in Sqlclient), do you have something complicated? That's right, this is really ok, NHibernate is also doing this. But if we do it directly, then the code is not well portability. If you change the database connection mode, you need to change the code, and you don't have a need to change any code. Of course, the SQL statement is except. As for the parameters, you can handle it through idbcommand.createparameter, here is not much. 4. Example The method of executing a SQL statement in NHibernate is executesql.
public IList ExecuteSQL (string query) {IList result = new ArrayList (); ISessionFactoryImplementor s = (ISessionFactoryImplementor) cfg.BuildSessionFactory (); IDbCommand cmd = s.ConnectionProvider.Driver.CreateCommand (); cmd.CommandText = query; IDbConnection conn = S.OpenConnection (); try {cmd.connection = conn; idiacuter = cmd.executeReader (); while (rs.read ()) {int fieldcount = rs.fieldcount; object [] values = new object [fieldcount]; For (int i = 0; i