grails笔记------Controller中直接使用SQL语句

grails的Controller中查询一般可以用 类名.findAll或者 类名.executeQuery()来查询

但是必须使用gql语句,gql与hql语句语法类似,但经我试用有些hql能使用的语法gql不能用,比如多表左右连接,所以我直接用jdbc写了

gql普通关联的语句如:

def xx =   Goodsinput.executeQuery("select (sum(i.gooEnter*i.gooEnterprice) - sum(o.gooDepletion*o.gooPrice)) as sumprice from Goodsinput i , Goodsdepletion o where i.gooName = o.gooName and i.shoId ='888888888888' and o.shoId = '888888888888' and i.gooName.id = 'SP1000000229'")

这是一条计算库存商品平均价的gql,经测试成功,但外连接 left outer join on 、 i.gooName = o.gooName(+)都不符合gql语法。

使用JDBC也很简单:

1.使用spring加载dataSource到Controller中。

      a.将apache的dbcp包放入grail的lib目录

      b.在conf/spring目录下resources中.配置bean:dataSourc

        注意:以前是xml的,现在是直接用groovy了

        代码如下:

groovy版:

            import org.apache.commons.dbcp.BasicDataSource
            beans = {
               dataSource(BasicDataSource) {
                driverClassName = "org.hsqldb.jdbcDriver"
               url = "jdbc:hsqldb:mem:devDB"
               username = "sa"
               password = ""
              }
   xml版:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="dataSource" class=" org.apache.commons.dbcp.BasicDataSource ">
     <property name="driverClassName">    <value>org.hsqldb.jdbcDriver</value></property>
     <property name="url">    <value>jdbc:hsqldb:hsql://localhost</value></property>
     <property name="username">    <value>sa</value></property>
     <property name="password">    <value></value></property>
</bean>
</beans>

      c.在Controller中定义dataSource,代码如下:

             def dataSource

2.获取连接,代码如下:

    def conn = dataSource.getConnection()

3.执行sql语句,代码如下:

      PreparedStatement ps = conn.prepareStatement("select * from customer");
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {

         println rs.getString("cus_name")

         }

   ok!这样就搞定了.

你可能感兴趣的:(spring,sql,HSQLDB,grails,groovy)