Cannot get MySQL assembly to load in powershell - mysql

I cannot get a connection to a linux mysql container running ubuntu on my local machine. I'm using powershell to create a mysql connection. Brand new to working with databases and putting in data so really no idea what I'm doing.
In the container, I've created a DB
mysql> CREATE DATABASE mydb;
Query OK, 1 row affected (0.04 sec)
mysql> CREATE TABLE test (id INT, text varchar(50), date_val date, date_time datetime);
mysql> USE mydb;
Database changed
mysql> CREATE TABLE test (id INT, text varchar(50), date_val date, date_time datetime);
Query OK, 0 rows affected (0.12 sec)
Testing the connection to the port the container was configured for from my local host
PS C:\Users\me> Test-NetConnection 127.0.0.1 -Port 3306
ComputerName : 127.0.0.1
RemoteAddress : 127.0.0.1
RemotePort : 3306
InterfaceAlias : Loopback Pseudo-Interface 1
SourceAddress : 127.0.0.1
TcpTestSucceeded : True
Here's my powershell script
[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$constr = "server=127.0.0.1:3306;port=3306;database=mydb;user id=root;password=P#ssw0rd"
$con = New-Object MySql.Data.MySqlclient.MySqlConnection
$con.ConnectionString = $constr
$con.Open()
$cmd = New-Object MySql.Data.MySqlClient.MySqlCommand
$cmd.CommandText = "INSERT INTO test VALUES(#id, #text, #date, #datetime)"
$cmd.Connection = $con
$cmd.Prepare()
$today = get-date
$cmd.Parameters("#id").Value = 1
$cmd.Parameters("#text").Value = "Text Value"
$cmd.Parameters("#date").Value = $today
$cmd.Parameters("#datetime").Value = $today
$cmd.ExecuteNonQuery()
$con.close()
This is the error that I get
Exception calling "Open" with "0" argument(s): "Unable to connect to any of the specified MySQL hosts."
At \\file\Tech\Dietrich\powershell scripts\VMware\Horizonview_session_count.ps1:24 char:1
+ $con.Open()
+ ~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : MySqlException
Exception calling "Prepare" with "0" argument(s): "The connection is not open."
At \\file\Tech\me\powershell scripts\VMware\Horizonview_session_count.ps1:28 char:1
+ $cmd.Prepare()
+ ~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
Method invocation failed because [MySql.Data.MySqlClient.MySqlCommand] does not contain a method named 'Parameters'.
At \\file\Tech\me\powershell scripts\VMware\Horizonview_session_count.ps1:30 char:1
+ $cmd.Parameters("#id").Value = 1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [MySql.Data.MySqlClient.MySqlCommand] does not contain a method named 'Parameters'.
At \\file\Tech\me\powershell scripts\VMware\Horizonview_session_count.ps1:31 char:1
+ $cmd.Parameters("#text").Value = "Text Value"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [MySql.Data.MySqlClient.MySqlCommand] does not contain a method named 'Parameters'.
At \\file\Tech\me\powershell scripts\VMware\Horizonview_session_count.ps1:32 char:1
+ $cmd.Parameters("#date").Value = $today
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [MySql.Data.MySqlClient.MySqlCommand] does not contain a method named 'Parameters'.
At \\file\Tech\me\powershell scripts\VMware\Horizonview_session_count.ps1:33 char:1
+ $cmd.Parameters("#datetime").Value = $today
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Exception calling "ExecuteNonQuery" with "0" argument(s): "Connection must be valid and open."
At \\file\Tech\me\powershell scripts\VMware\Horizonview_session_count.ps1:34 char:1
+ $cmd.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException

it was my syntax. This worked (although I still get this error...the table populates)
Method invocation failed because [MySql.Data.MySqlClient.MySqlCommand] does not contain a method named 'Parameters'.
At \\ae-file\Tech\Dietrich\powershell scripts\VMware\Horizonview_session_count.ps1:28 char:1
+ $cmd.Parameters("#id").Value = 1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$constr = "server=127.0.0.1;port=3306;database=mydb;user id=root;password=P#ssw0rd"
$con = New-Object MySql.Data.MySqlclient.MySqlConnection
$con.ConnectionString = $constr
$con.Open()
$cmd = New-Object MySql.Data.MySqlClient.MySqlCommand
$cmd.CommandText = "INSERT INTO test VALUES(#id, #text, #date, #datetime)"
$cmd.Connection = $con
$cmd.Prepare()
$today = get-date
$cmd.Parameters("#id").Value = 1
$cmd.Parameters.AddWithValue("#id", 1)
$cmd.Parameters.AddWithValue("#text", $totalSessions.count)
$cmd.Parameters.AddWithValue("#date", $today)
$cmd.Parameters.AddWithValue("#datetime", $today)
$cmd.ExecuteNonQuery()
$con.close()
Result
SourceVersion : Default
ParameterName : #id
Direction : Input
IsNullable : False
MySqlDbType : Int32
Precision : 0
Scale : 0
Size : 0
Value : 1
PossibleValues :
SourceColumn :
SourceColumnNullMapping : False
DbType : Int32
SourceVersion : Default
ParameterName : #text
Direction : Input
IsNullable : False
MySqlDbType : Int32
Precision : 0
Scale : 0
Size : 0
Value : 241
PossibleValues :
SourceColumn :
SourceColumnNullMapping : False
DbType : Int32
SourceVersion : Default
ParameterName : #date
Direction : Input
IsNullable : False
MySqlDbType : DateTime
Precision : 0
Scale : 0
Size : 0
Value : 4/21/2020 4:34:40 PM
PossibleValues :
SourceColumn :
SourceColumnNullMapping : False
DbType : DateTime
SourceVersion : Default
ParameterName : #datetime
Direction : Input
IsNullable : False
MySqlDbType : DateTime
Precision : 0
Scale : 0
Size : 0
Value : 4/21/2020 4:34:40 PM
PossibleValues :
SourceColumn :
SourceColumnNullMapping : False
DbType : DateTime
1
Table
mysql> select * from test;
+------+------------+------------+---------------------+
| id | text | date_val | date_time |
+------+------------+------------+---------------------+
| 1 | Text Value | 2020-04-21 | 2020-04-21 15:54:54 |
| 1 | Text Value | 2020-04-21 | 2020-04-21 15:57:05 |
| 1 | Text Value | 2020-04-21 | 2020-04-21 16:02:12 |
+------+------------+------------+---------------------+
3 rows in set (0.00 sec)

Related

Sort lua table based on nested json value

We have a key-value pair in redis consisting of a key with a JSON object as a value with various information;
"node:service:i-01fe0d69c343734" :
"{\"port\":\"32781\",
\"version\":\"3.0.2\",
\"host-instance-id\":\"i-01fe0d69c2243b366\",
\"last-checkin\":\"1492702508\",
\"addr\":\"10.0.0.0\",
\"host-instance-type\":\"m3.large\"}"
Is it possible to sort the table based on the last-checkin time of the value?
Here is my solution to your problem, using the quick sort algorithm, before doing a little correction of your input (as I understood it):
-----------------------------------------------------
local json = require("json")
function quicksort(t, sortname, start, endi)
start, endi = start or 1, endi or #t
sortname = sortname or 1
if(endi - start < 1) then return t end
local pivot = start
for i = start + 1, endi do
if t[i][sortname] <= t[pivot][sortname] then
local temp = t[pivot + 1]
t[pivot + 1] = t[pivot]
if(i == pivot + 1) then
t[pivot] = temp
else
t[pivot] = t[i]
t[i] = temp
end
pivot = pivot + 1
end
end
t = quicksort(t, sortname, start, pivot - 1)
return quicksort(t, sortname, pivot + 1, endi)
end
---------------------------------------------------------
-- I manually added delimeter ","
-- and name "node:service..." must be different
str = [[
{
"node:service:i-01fe0d69c343731" :
"{\"port\":\"32781\",
\"version\":\"3.0.2\",
\"host-instance-id\":\"i-01fe0d69c2243b366\",
\"last-checkin\":\"1492702506\",
\"addr\":\"10.0.0.0\",
\"host-instance-type\":\"m3.large\"}"
,
"node:service:i-01fe0d69c343732" :
"{\"port\":\"32781\",
\"version\":\"3.0.2\",
\"host-instance-id\":\"i-01fe0d69c2243b366\",
\"last-checkin\":\"1492702508\",
\"addr\":\"10.0.0.0\",
\"host-instance-type\":\"m3.large\"}"
,
"node:service:i-01fe0d69c343733" :
"{\"port\":\"32781\",
\"version\":\"3.0.2\",
\"host-instance-id\":\"i-01fe0d69c2243b366\",
\"last-checkin\":\"1492702507\",
\"addr\":\"10.0.0.0\",
\"host-instance-type\":\"m3.large\"}"
,
"node:service:i-01fe0d69c343734" :
"{\"port\":\"32781\",
\"version\":\"3.0.2\",
\"host-instance-id\":\"i-01fe0d69c2243b366\",
\"last-checkin\":\"1492702501\",
\"addr\":\"10.0.0.0\",
\"host-instance-type\":\"m3.large\"}"
}
]]
-- remove unnecessary \
str = str:gsub('"{','{'):gsub('}"','}'):gsub('\\"','"')
local t_res= json.decode(str)
-- prepare table before sorting
local t_indexed = {}
for k,v in pairs(t_res) do
v["node-service"] = k
t_indexed[#t_indexed+1] = v
end
-- algoritm quicksort realised only for indexed table
local t_sort= quicksort(t_indexed, "last-checkin")
for k,v in pairs(t_sort) do
print( k , v["node-service"] , v["port"], v["version"], v["host-instance-id"], v["last-checkin"] , v["addr"], v["host-instance-type"] )
end
console:
1 node:service:i-01fe0d69c343734 32781 3.0.2 i-01fe0d69c2243b366 1492702501 10.0.0.0 m3.large
2 node:service:i-01fe0d69c343731 32781 3.0.2 i-01fe0d69c2243b366 1492702506 10.0.0.0 m3.large
3 node:service:i-01fe0d69c343733 32781 3.0.2 i-01fe0d69c2243b366 1492702507 10.0.0.0 m3.large
4 node:service:i-01fe0d69c343732 32781 3.0.2 i-01fe0d69c2243b366 1492702508 10.0.0.0 m3.large

How can make json output

I want make json output using below code.
But I can't make json output
below is my code but not work
===================================================================
#!/usr/bin/perl
print "{\n";
print "\t\"data\":[\n\n";
for (`cat usable | awk 'NF>0 && NR>8 && NR < 15'`)
{
($poolname, $devconfig, $unablegbs, $freegbs, $usedgbs, $full, $comp) = m/ (\S+)/;
print "\t,\n" if not $first;
$first = 0;
print "\t{\n";
print "\t\t\"{#POOLSNAME}\":\"$poolname\",\n";
print "\t\t\"{#DEVCOFIG}\":\"$devconfig\",\n";
print "\t\t\"{#UNABLEGBS}\":\"$unablegbs\",\n";
print "\t\t\"{#FREEGBS}\":\"$freegbs\",\n";
print "\t\t\"{#USEDGBS}\":\"$usedgbs\",\n";
print "\t\t\"{#FULL}\":\"$full\",\n";
print "\t\t\"{#COMP}\":\"$comp\",\n";
print "\t}\n";
}
print "\n\t]\n";
print "}\n";
===================================================================
input file is below
Symmetrix ID: 000000000000
S Y M M E T R I X P O O L S
---------------------------------------------------------------------------
Pool Flags Dev Usable Free Used Full Comp
Name PTECSL Config GBs GBs GBs (%) (%)
------------ ------ ------------ ---------- ---------- ---------- ---- ----
SAS600_R1 TFFDEI RAID-5(3+1) 78725.1 160.3 64.8 94 0
SAS600_R2 TFFDEI RAID-4(3+1) 725.1 120.3 666.8 83 0
SAS600_R3 TFFDEI RAID-3(3+1) 7825.1 1260.3 6564.8 34 0
SAS600_R4 TFFDEI RAID-2(3+1) 7875.1 160.3 664.8 4 0
SAS600_R5 TFFDEI RAID-1(3+1) 872.1 1210.3 6564.8 1 0
Total ---------- ---------- ---------- ---- --- -
GBs 78725.1 12160.3 66564.8 84 0
Legend:
(P)ool Type:
S = Snap, R = Rdfa DSE T = Thin
(T)echnology:
S = SATA, F = Fibre Channel, E = Enterprise Flash Drive, M = Mixed, - = N/A
Dev (E)mulation:
F = FBA, A = AS400, 8 = CKD3380, 9 = CKD3390, - = N/A
(C)ompression:
E = Enabled, D = Disabled, N = Enabling, S = Disabling, - = N/A
(S)tate:
E = Enabled, D = Disabled, B = Balancing
Disk (L)ocation:
I = Internal, X = External, M = Mixed, - = N/A`
===================================================================
OUTPUT want look like below
{
"{#POOLINDEX1}":"SAS600_R5","{#RAIDVALUE1}":"RAID-5(3+1)"," {#USABLEVALUE1}":"725.1","{#FREEVALUE1}":"160.3","{#USEDVALUE1}":"564.8"}," {#FULLVALUE1}":"84%","{#COMPVALUE1}":"0"},
"{#POOLINDEX2}":"SAS600_R3","{#RAIDVALUE2}":"RAID-3(3+1)",{#USABLEVALUE2}":"78725.1","{#FREEVALUE2}":"1160.3","{#USEDVALUE2}":"6564.8"}," {#FULLVALUE2}":"54%","{#COMPVALUE2}":"0"},
"{#POOLINDEX3}":"SAS600_R2","{#RAIDVALUE3}":"RAID-1(3+1)"," {#USABLEVALUE3}":"7725.1","{#FREEVALUE3}":"12160.3","{#USEDVALUE3}":"66564.8"}," {#FULLVALUE3}":"8%","{#COMPVALUE3}":"0"}
}
First of all. Your program almost works. You just need a g modifier on your regular expression:
($poolname, $devconfig, $unablegbs, $freegbs, $usedgbs, $full, $comp) = m/ (\S+)/g;
And remove the , after $comp to be valid JSON.
Your program could do with a couple of improvements. I would suggest
Using JSON package to create JSON.
Using perl inline syntax, instead of calling cat and awk. Perl has support for everything that you can do with awk. If you continue to use an external call then stop with cat abuse.
I have two answers to this question:
use the JSON module to assemble JSON. It's less painful.
this looks like the Symmetrix CLI output. Set -output XML and you'll get machine readable output. XML not JSON, but it's actually easier to convert from one to the other than hand parse anyway.
To answer your question as asked though:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
my #header = qw ( name flags raid usable_gb free_gb used_gb full_perc comp_perc );
my $stuff;
while ( <DATA> ) {
my %this_row;
if ( m/RAID/ ) {
my #fields = split;
#this_row{#header} = #fields;
push ( #$stuff, \%this_row );
}
}
print to_json ( $stuff, { pretty => 1 } );
__DATA__
Symmetrix ID: 000000000000
S Y M M E T R I X P O O L S
---------------------------------------------------------------------------
Pool Flags Dev Usable Free Used Full Comp
Name PTECSL Config GBs GBs GBs (%) (%)
------------ ------ ------------ ---------- ---------- ---------- ---- ----
SAS600_R1 TFFDEI RAID-5(3+1) 78725.1 160.3 64.8 94 0
SAS600_R2 TFFDEI RAID-4(3+1) 725.1 120.3 666.8 83 0
SAS600_R3 TFFDEI RAID-3(3+1) 7825.1 1260.3 6564.8 34 0
SAS600_R4 TFFDEI RAID-2(3+1) 7875.1 160.3 664.8 4 0
SAS600_R5 TFFDEI RAID-1(3+1) 872.1 1210.3 6564.8 1 0
Total ---------- ---------- ---------- ---- --- -
GBs 78725.1 12160.3 66564.8 84 0
Legend:
(P)ool Type:
S = Snap, R = Rdfa DSE T = Thin
(T)echnology:
S = SATA, F = Fibre Channel, E = Enterprise Flash Drive, M = Mixed, - = N/A
Dev (E)mulation:
F = FBA, A = AS400, 8 = CKD3380, 9 = CKD3390, - = N/A
(C)ompression:
E = Enabled, D = Disabled, N = Enabling, S = Disabling, - = N/A
(S)tate:
E = Enabled, D = Disabled, B = Balancing
Disk (L)ocation:
I = Internal, X = External, M = Mixed, - = N/A`
Output:
[
{
"full_perc" : "94",
"flags" : "TFFDEI",
"comp_perc" : "0",
"name" : "SAS600_R1",
"used_gb" : "64.8",
"free_gb" : "160.3",
"usable_gb" : "78725.1",
"raid" : "RAID-5(3+1)"
},
{
"flags" : "TFFDEI",
"comp_perc" : "0",
"name" : "SAS600_R2",
"full_perc" : "83",
"usable_gb" : "725.1",
"raid" : "RAID-4(3+1)",
"used_gb" : "666.8",
"free_gb" : "120.3"
},
{
"usable_gb" : "7825.1",
"raid" : "RAID-3(3+1)",
"free_gb" : "1260.3",
"used_gb" : "6564.8",
"name" : "SAS600_R3",
"flags" : "TFFDEI",
"comp_perc" : "0",
"full_perc" : "34"
},
{
"free_gb" : "160.3",
"used_gb" : "664.8",
"raid" : "RAID-2(3+1)",
"usable_gb" : "7875.1",
"full_perc" : "4",
"name" : "SAS600_R4",
"comp_perc" : "0",
"flags" : "TFFDEI"
},
{
"usable_gb" : "872.1",
"raid" : "RAID-1(3+1)",
"used_gb" : "6564.8",
"free_gb" : "1210.3",
"flags" : "TFFDEI",
"comp_perc" : "0",
"name" : "SAS600_R5",
"full_perc" : "1"
}
]

XSuperObject Object Show

I have one line json type:
Rows : [{ scan : 12, find : 6, fImg : 2 }]
i am using xsuperobject.
i want to show Rows.scan
if it is not a object i can show like X['scan'];
i searched this page : https://code.google.com/p/x-superobject/source/browse/wiki/Sample.wiki
*Sample 2*
{{{
const
JSN = '{ '+
' "adresses": [ '+
' { '+
' "adress": "blabla", '+
' "city": "Antalya", '+
' "pc": 7160 '+
' },'+
' { '+
' "adress": "blabla", '+
' "city": "Adana", '+
' "pc": 1170 '+
' } '+
' ] '+
'}';
var
X, Obj: ISuperObject;
J: Integer;
begin
X := TSuperObject.Create(JSN);
with X.A['adresses'] do
for J := 0 to Lenght -1 do
begin
Obj := O[J];
Obj.First;
while not Obj.EoF do
begin
Memo1.Lines.Add( Obj.CurrentKey + ' = ' + VarToStr(Obj.CurrentValue.AsVariant));
Obj.Next;
end;
Memo1.Lines.Add('------');
end;
end;
}}}
*OR (Enumerator)*
{{{
var
X: ISuperObject;
AMember,
OMember: IMember;
begin
X := TSuperObject.Create(JSN);
for AMember in X.A['adresses'] do
begin
for OMember in AMember.AsObject do
Memo1.Lines.Add(OMember.Name + ' = ' + OMember.ToString);
Memo1.Lines.Add('------');
end;
}}}
*Output*
{{{
adress = blabla
city = Antalya
pc = 7160
------
adress = blabla
city = Adana
pc = 1170
}}}
------
He gave a this example, but this is a multiple. I have one line. How can i do it?
procedure TForm4.Button1Click(Sender: TObject);
var
json: ISuperObject;
begin
json := SO('{"Rows":[{"scan":12,"find":6,"fImg":2}]}');
ShowMessage(json.A['Rows'].O[0].I['scan'].ToString());
end;
If your JSon is multilevel you iterate over the level you want to retrieve,here 'Rows'
ROW1= '{Rows : [{ scan : 12, find : 6, fImg : 2 }]}';
var
X: ISuperObject;
AMember,
OMember: IMember;
begin
X := TSuperObject.Create(ROW1);
for AMember in X.A['Rows'] do
begin
for OMember in AMember.AsObject do
Memo1.Lines.Add(OMember.Name + ' = ' + OMember.ToString);
Memo1.Lines.Add('------');
end;
end;
For a simple object you just iterate over then object itself
ROW2= '{ scan : 12, find : 6, fImg : 2 }';
var
X: ISuperObject;
AMember,
OMember: IMember;
begin
X := TSuperObject.Create(ROW2);
for OMember in X do
Memo1.Lines.Add(OMember.Name + ' = ' + OMember.ToString);
end;

Grails 2.3.2: findOrCreate using Enums in Bootstrap

I am having troubles with using the findOrCreateBy method in the Bootstrap.groovy.
class Guest {
String firstname
String lastname
Gender gender
static constraints = {
firstname blank: false
lastname blank: false
gender nullable: false
}
}
enum Gender {
MALE('male'), FEMALE('female')
final String v
Gender(String s) { v = s }
}
And in the Bootstrap I try to create Guests if they do not exist yet.
Guest guest = Guest.findOrCreateByFirstnameAndLastnameAndGender(firstname, lastname, Gender.MALE)
guest.save()
The first time I run the app against MySQL everything works fine. The apps starts without any error. If I run the app a second time (this time with guest in the database) I get the following failure.
| Error 2013-11-17 14:27:37,621 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing the application: Unknown name value [1] for enum class [ch.silviowangler.ch.cisposiamo.Gender]
Message: Unknown name value [1] for enum class [ch.silviowangler.ch.cisposiamo.Gender]
Line | Method
->> 105 | methodMissing in org.grails.datastore.gorm.GormStaticApi
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 106 | createGuest in BootStrap
| 102 | createGuest . . . . . . . . . . in ''
| 66 | doCall in BootStrap$_closure1
| 308 | evaluateEnvironmentSpecificBlock in grails.util.Environment
| 301 | executeForEnvironment in ''
| 277 | executeForCurrentEnvironment . . in ''
| 262 | run in java.util.concurrent.FutureTask
| 1145 | runWorker . . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run . . . . . . . . . . . . . . in java.lang.Thread
It seems the the first time Gorm writes values '0' and '1' to the database. In the second run it fails to convert these 0 and 1 into the corresponding enum value. Can anybody tell me what I am doing wrong?
Try this - Add the parameter generateSimpleParameterMetadata=true to your url connect string,
...
url = "jdbc:mysql://localhost/bootstraptest?generateSimpleParameterMetadata=true"
...
This has something to do with the way the driver interprets the enum meta data (frankly i don't understand it well) see http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html
This solution is very db specific, so you don't need any other changes
Note that the actual enum label will now be stored in the database ('NEW', 'WIP', 'DONE' instead of 0, 1, 2)
I think this is related to mysql, I dont have mysql to test it against and never worked with mysql, but try to specifically map the enum, like this:
static mapping = {
...
gender column: 'gender', sqlType: 'enum', name: 'gender'
}
ref
And if you are manually creating your database table , try to create the enum for your columns similar to this:
CREATE TABLE sizes (
name ENUM('small', 'medium', 'large')
);
ref
This is another article that can help here
I suggest to change mapping using IdentityEnumType:
static mapping = {
...
gender column: 'gender', type: IdentityEnumType
}
Modify your Enum, by adding id to it:
public enum Gender {
MALE (1, "male"),
FEMALE (2, "female"),
final Integer id
final String value
Gender (Integer id, String value) {
this.id = id
this.value = value
}
String getValue() {
return value
}
String toString() {
return name()
}
String getKey() {
return name()
}
That should help you.

Grails or Hibernate not creating missing table

I'm new to Grails so forgive my ignorance--if other info is helpful I'll do my best to get it posted.
I've created a single domain model class ToolKitComponent that is defined as:
class ToolKitComponent {
String componentName
String componentVersion
int componentDownloads
Date compnentLastUpdate
static constraints = {
}
}
I have a controller that I just want to test the ORM by persisting an example, so here's the contents of the controller:
def index() {
ToolKitComponent i = new ToolKitComponent()
i.setComponentName("TestComponent")
i.setComponentVersion("v1.10")
i.setComponentDownloads(1)
i.setCompnentLastUpdate(new Date())
i.save()
}
I've installed the MySql database plugin and updated my DataSource.groovy to:
dataSource {
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
loggingSql = true
}
// other settings
environments {
development {
dataSource {
String dbCreate = "create"
String url = "jdbc:mysql://localhost/testDataBase"
String username = "myUser"
String password = "myPass"
}
}
}
I've created the database testDataBase and granted all to the username.
When I run the application, I get:
Hibernate: insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?)
| Error 2012-07-11 20:01:52,727 [http-bio-8080-exec-2] ERROR util.JDBCExceptionReporter - Table "TOOL_KIT_COMPONENT" not found; SQL statement:
insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?) [42102-164]
| Error 2012-07-11 20:01:52,752 [http-bio-8080-exec-2] ERROR errors.GrailsExceptionResolver - JdbcSQLException occurred when processing request: [GET] /TestProject/
Table "TOOL_KIT_COMPONENT" not found; SQL statement:
insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?) [42102-164]. Stacktrace follows:
Message: Table "TOOL_KIT_COMPONENT" not found; SQL statement:
insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?) [42102-164]
Line | Method
->> 329 | getJdbcSQLException in org.h2.message.DbException
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 169 | get in ''
| 146 | get . . . . . . . . in ''
| 4753 | readTableOrView in org.h2.command.Parser
| 4731 | readTableOrView . . in ''
| 954 | parseInsert in ''
| 375 | parsePrepared . . . in ''
| 279 | parse in ''
| 251 | parse . . . . . . . in ''
| 217 | prepareCommand in ''
| 415 | prepareLocal . . . in org.h2.engine.Session
| 364 | prepareCommand in ''
| 1121 | prepareCommand . . in org.h2.jdbc.JdbcConnection
| 71 | <init> in org.h2.jdbc.JdbcPreparedStatement
| 267 | prepareStatement . in org.h2.jdbc.JdbcConnection
| 1051 | prepareStatement in ''
| 508 | prepareStatement . in org.apache.commons.dbcp.DelegatingConnection
| 400 | prepareStatement in org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper
| 11 | index . . . . . . . in TestProject.HomeController
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
I'm using Grails 2.0.4.
Any help is appreciated!
Take away the String in your datasource definition
environments {
development {
dataSource {
dbCreate = "create"
url = "jdbc:mysql://localhost/testDataBase"
username = "myUser"
password = "myPass"
}
}
}