GroovySQL with Mysql db


/ Published in: Groovy
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #!/usr/bin/env groovy
  2. import groovy.sql.Sql
  3.  
  4. sql = Sql.newInstance('jdbc:mysql://localhost:3306/test', 'root', '', 'com.mysql.jdbc.Driver')
  5.  
  6. /*println 'Show all tables'
  7. sql.eachRow('show tables'){ row ->
  8. println row[0]
  9. }
  10. println ''*/
  11.  
  12. println 'Create user table'
  13. sql.execute('''
  14. create table if not exists user(
  15. id int auto_increment primary key,
  16. name varchar(63) not null,
  17. password varchar(35) not null
  18. )
  19. ''')
  20.  
  21. println 'Create category table'
  22. sql.execute('''
  23. create table if not exists category(
  24. id int auto_increment primary key,
  25. name varchar(63) not null,
  26. parent_id int null
  27. )
  28. ''')
  29.  
  30. println 'Create product table'
  31. sql.execute('''
  32. create table if not exists product(
  33. id int auto_increment primary key,
  34. category_id int not null,
  35. name varchar(63) not null,
  36. price decimal(10,2) not null,
  37. description text null
  38. )
  39. ''')
  40.  
  41. //Generate some data.
  42. insertUser = 'insert into user(name, password) values(?, ?)'
  43. for(idx in 1..3){
  44. println "Inserting user: tester$idx"
  45. //sql.executeInsert(insertUser, ["tester", "a"]) //Doesn't work???
  46. sql.execute(insertUser, ["tester" + idx, "a"])
  47. }
  48.  
  49. insertCategory = 'insert into category(name, parent_id) values(?,?)'
  50. for(idx in 1..3){
  51. println "Inserting category: cat$idx"
  52. sql.execute(insertCategory, ["cat$idx".toString(), null]) //toString is needed to persist.
  53. }
  54. lastCatId = sql.firstRow('select last_insert_id()')[0]
  55.  
  56. insertProduct = 'insert into product(category_id, name, price, description) values(?,?,?,?)'
  57. for(idx in 1..50){
  58. println "Inserting product: product$idx"
  59. sql.execute(insertProduct, [lastCatId, "product"+idx, idx * Math.random(), "Just a test product item."])
  60. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.