srinath
srinath

Reputation: 399

Sql query for insert in grails

How to execute plain sql in grails . I need to use sql query for inserting new record in database .

How can we achieve this with out using HQL and gorm relations .

thanks

Upvotes: 11

Views: 13886

Answers (2)

Burt Beckwith
Burt Beckwith

Reputation: 75681

groovy.sql.Sql simplifies the details of doing JDBC queries. In a Grails app you'd use the constructor that takes a DataSource:

import groovy.sql.Sql
...
class FooService {

   def dataSource
   ...
   def runSqlQuery(...) {
      Sql sql = new Sql(dataSource)
      sql.executeInsert("insert into ...")
      ...
   }
}

See these links for usage tips:

http://docs.codehaus.org/display/GROOVY/Tutorial+6+-+Groovy+SQL

http://www.ibm.com/developerworks/java/library/j-pg01115.html

Upvotes: 16

Jared
Jared

Reputation: 39913

You can do this by calling the Hibernate Session.createSQLQuery() method. First you need to get the Hibernate session then use that session to execute SQL. See this link to see how to get a Hibernate session from your grails app. Then see this link for info on using Hibernate to execute SQL.

Upvotes: 5

Related Questions