How to convert H2Database database file to MySQL database .sql file? - mysql

I have some data in H2Database file and I want to convert it to MySQL .sql database file. What are the methods I can follow?

In answer to Thomas Mueller, SquirrelSQL worked fine for me.
Here is the procedure for Windows to convert a H2 database:
Go to "drivers list", where everything is red by default.
Select "H2" driver, and specify the full path to "h2-1.3.173.jar" (for
example) in "Extra Class Path". The H2 driver should display a blue
check in the list.
Select your target driver (PostgreSQL, MySQL), and
do the same, for example for PostgreSQL, specify the full path to
"postgresql-9.4-1201.jdbc41.jar" in Extra Class Path.
Go to "Aliases", then click on "+" for H2 : configure your JDBC chain, for example copy/paste the jdbc chain you obtain when you launch H2, and do the same for your target database: click on "+", configure and "test".
When you double click on your alias, you should see everything inside your database in a new Tab. Go to the tables in source database, do a multi-select on all your tables and do a right-click : "Copy Table".
Go to your target database from Alias, and do a "Paste Table". When all tables are copied altogether, the foreign key references are also generated.
Check your primary keys : from H2 to PostgreSQL, I lost the Primary Key constraints, and the auto-increment capability.
You could also rename columns and tables by a right click : "refactor". I used it to rename reserved words columns after full copy, by disabling name check in options.
This worked well for me.

The SQL script generated by the H2 database is not fully compatible with the SQL supported by MySQL. You would have to change the SQL script manually. This requires that you know both H2 and MySQL quite well.
To avoid this problem, an alternative, probably simpler way to copy the data from H2 to MySQL is to use a 3rd party tool such as the SQuirreL SQL together with the SQuirreL DB Copy Plugin plugin. (First you need to install SQuirreL SQL and on top of that the SQuirreL DB Copy Plugin.)

I created a Groovy script that does the migration from h2 to mysql. From there you could do a mysqldump. It requires that the tables exists in the Mysql database. It should work for ohter DBMS with minor changes.
#Grapes(
[
#Grab(group='mysql', module='mysql-connector-java', version='5.1.26'),
#Grab(group='com.h2database', module='h2', version='1.3.166'),
#GrabConfig(systemClassLoader = true)
])
import groovy.sql.Sql
def h2Url='jdbc:h2:C:\\Users\\xxx\\Desktop\\h2\\sonardata\\sonar'
def h2User='sonar'
def h2Passwd='sonar'
def mysqlUrl='jdbc:mysql://10.56.xxx.xxx:3306/sonar?useunicode=true&characterencoding=utf8&rewritebatchedstatements=true'
def mysqlUser='sonar'
def mysqlPasswd='xxxxxx'
def mysqlDatabase='sonar'
sql = Sql.newInstance(h2Url, h2User, h2Passwd, 'org.h2.Driver' )
def tables = [:]
sql.eachRow("select * from information_schema.columns where table_schema='PUBLIC'") {
if(!it.TABLE_NAME.endsWith("_MY")) {
if (tables[it.TABLE_NAME] == null) {
tables[it.TABLE_NAME] = []
}
tables[it.TABLE_NAME] += it.COLUMN_NAME;
}
}
tables.each{tab, cols ->
println("processing $tab")
println("droppin $tab"+"_my")
sql.execute("DROP TABLE IF EXISTS "+tab+"_my;")
sql.execute("create linked table "+tab+"_my ('com.mysql.jdbc.Driver', '"+mysqlUrl+"', '"+mysqlUser+"', '"+mysqlPasswd+"', '"+mysqlDatabase+"."+tab.toLowerCase()+"');")
sql.eachRow("select count(*) as c from " + tab + "_my"){println("deleting $it.c entries from mysql table")}
result = sql.execute("delete from "+tab+"_my")
colString = cols.join(", ")
sql.eachRow("select count(*) as c from " + tab){println("starting to copy $it.c entries")}
sql.execute("insert into " + tab + "_my ("+colString+") select "+colString+" from " + tab)
}

The H2 database allows you to create a SQL script using the SCRIPT SQL statement or the Script command line tool. Possibly you will need to tweak the script before you can run it against the MySQL database.

You can use fullconvert to convert database. it's easy to use.
Follow steps shown here
https://www.fullconvert.com/howto/h2-to-mysql

Related

'Relation does not exist' error after transferring to PostgreSQL

I have transfered my project from MySQL to PostgreSQL and tried to drop the column as result of previous issue, because after I removed the problematic column from models.py and saved. error didn't even disappear. Integer error transferring from MySQL to PostgreSQL
Tried both with and without quotes.
ALTER TABLE "UserProfile" DROP COLUMN how_many_new_notifications;
Or:
ALTER TABLE UserProfile DROP COLUMN how_many_new_notifications;
Getting the following:
ERROR: relation "UserProfile" does not exist
Here's a model, if helps:
class UserProfile(models.Model):
user = models.OneToOneField(User)
how_many_new_notifications = models.IntegerField(null=True,default=0)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
I supposed it might have something to do with mixed-case but I have found no solution through all similar questions.
Yes, Postgresql is a case aware database but django is smart enough to know that. It converts all field and it generally converts the model name to a lower case table name. However the real problem here is that your model name will be prefixed by the app name. generally django table names are like:
<appname>_<modelname>
You can find out what exactly it is by:
from myapp.models import UserProfile
print (UserProfile._meta.db_table)
Obviously this needs to be typed into the django shell, which is invoked by ./manage.py shell the result of this print statement is what you should use in your query.
Client: DataGrip
Database engine: PostgreSQL
For me this worked opening a new console, because apparently from the IDE cache it was not recognizing the table I had created.
Steps to operate with the tables of a database:
Database (Left side panel of the IDE) >
Double Click on PostgreSQL - #localhost >
Double Click on the name of the database >
Right click on public schema >
New > Console
GL

How to resolve SQL table with prefix in PhpStorm?

I'm working on PhpStorm to develop my Prestashop websites and I can't resolve this issue. I work on localhost and successfully connected PhpStorm to my MySQL Server.
Now PhpStorm throws warnings like "unable to resolve table '${_DB_PREFIX_}cms'". Prestashop uses prefixes for table names and it seems PhpStorm can't resolve those tables with prefixes.
Is there a workaround for this ?
Here is a code exemple from Prestashop-1.6 sources :
$sql = 'SELECT c.`id_cms`, cl.`meta_title`, cl.`link_rewrite`
FROM `'._DB_PREFIX_.'cms` c
INNER JOIN `'._DB_PREFIX_.'cms_shop` cs
ON (c.`id_cms` = cs.`id_cms`)
INNER JOIN `'._DB_PREFIX_.'cms_lang` cl
ON (c.`id_cms` = cl.`id_cms`)
WHERE c.`id_cms_category` = '.(int)$id_cms_category.'
AND cs.`id_shop` = '.(int)$id_shop.'
AND cl.`id_lang` = '.(int)$id_lang.
$where_shop.'
AND c.`active` = 1
ORDER BY `position`';
The reason why this isn't work is because you are most likely only loading one schema, you need to load the information_schema.*
To do this, go to the database tab in the top right and where you have added your MySQL database right click and select properties.
Now you'll have a screen called Data Sources and Drivers, it should open on a tab called General, click the third tab called Schemas and and add information_schema.* to this list of loaded Schemas.
Click apply and okay and then PhpStorm will now know your database structure and then be intelligently able to work with you, therefor removing all the errors.
Edit: As mentioned here, this has been fixed in PhpStorm 2018.2, but only for constants.
I have a solution that doesn't involve throwing your IDE away. :)
However, a word of caution: it's an ugly hackā„¢ that comes without guarantees.
Assuming you already have a connection to the db in PhpStorm, generate the ddl for the desired db (Right Click on the connection -> SQL Scripts -> Generate DDL to Clipboard):
Paste the content into some sql file somewhere inside your project. You should probably gitignore this file.
Replace all the tables' prefix in this ddl file with the one from your code. Use the PhpStorm typehint as a guideline. For example '._DB_PREFIX_.'cms would become ${_DB_PREFIX_}cms:
Note that you may have to use backticks to avoid breaking sql syntax due to curly brackets.
Add the ddl to your phpstorm project:
Everything should now work:
Add this comment above the $sql query.
/** #noinspection SqlResolve */
This will suppress the warning only for this statement.
For future readers, this is now supported:
https://www.jetbrains.com/help/phpstorm/2021.1/ide-advanced-metadata.html#set-up-dynamic-prefixes-for-table-names-in-sql-language-injections
.phpstorm.meta.php
<?php
namespace PHPSTORM_META {
override(
// Virtual function to indicate that all SQL
// injections will have the following replacement rules.
sql_injection_subst(),
map([
'{' => "", // all `{` in injected SQL strings will be replaced with a prefix
'}' => '', // all `}` will be replaced with an empty string
]));
}
Edit: At time of writing (2016) there was no solution to this issue. But since 2018, as mentioned in Christian's answer, you can now use constants in SQL queries.
Actually there is no way to handle that. But you may disable inspection for such warning.
Open File > Settings > Editor > Inspections
Expand SQL
Uncheck Unresolved reference

How to access sql database from website?

How to access sql database which is at e.g
http://localhost/test.php?blah/blah/blah.sql
or Online using ADO connection or something?
I use
PHP Triad (PHP, Apache 1.3.23, MySQL)
Delphi 7
I've searched google but I did not find anything.
at *. mdb I usually use the following ways.
ADOTable1.ConnectionString: = 'Provider = Microsoft.Jet.OLEDB.4.0;' +
' Data Source =' +
ExtractFilePath (Application.ExeName) +
'data.mdb; Persist Security Info = False';
My question is the core principal example below:
I took part database layout direction.
e.g:
Source = '+ ExtractFilePath (Application.ExeName) +' data.mdb;
or
Source = 'D: \ Test \ data.mdb';
or
Source = 'Drive \ Directory \ Filename.Extension';
how to change the above example to be.
Source = 'http:// localhost/Test/Data.db';
and I just want to know how to connect Ado / components that can be used to import data from MySql and then sent to the columns in DBGrid, so I can Add, Edit and delete existing data in MySql table through Delphi.
NB: I do not know the composition of the MySql table, because I usually just use *. Mdb.
- If the PHP script I've encountered a lot of tutorials, but in Delphi not found.

How to remove "CREATE DATABASE IF NOT EXISTS" statement from Export in phpMyAdmin 4?

I'm using phpMyAdmin 4.0.2 and seems when doing an export over a whole DB, by default it adds the statement "CREATE DATABASE IF NOT EXISTS" in the beginning of the export SQL.
I wasn't able to find a config option or any option to disable that... So is there a way to disable that and not have that statement in my exports by default?
This behavior did not happen by default in version 3. A quick fix, actually a hack and thus not the desirable solution, is to edit the export class file located in libraries/plugins/export/ExportSql.class.php and force the CREATE and USE statements to be commented out by adding "-- " before them, as such:
Line 709
$create_query = '-- CREATE DATABASE IF NOT EXISTS '
Line 734
'-- USE ' . PMA_Util::backquoteCompat($db, $compat)
Edit: There's a drawback, and that is if you export one or more entire databases (not just some or all the tables inside a database), then the CREATE and USE statements appear commented also.
A better idea as opposed to Hermes's answer would be to edit the file ./export.php ( Mind you: not db_export.php ).
On line 724 ( in phpMyAdmin 4.0.4 ) you'll find the lines:
if (! $export_plugin->exportDBCreate($db)) {
break;
}
You can comment or remove them to skip the creation of the create database statements ( Which in my opinion is also neater then having 2 commented lines in the export ).
Like so:
/*
if (! $export_plugin->exportDBCreate($db)) {
break;
}
*/
The rows above only apply to exporting a single database ( On line 720, you'll find: } elseif ($export_type == 'database') { ). So you won't break full server exports.
What I do is I first select the database on the left sidebar, and then click the Export option. The dump file doesn't contain the CREATE DATABASE statement.
One quick warning, this works for me, but I haven't analyzed if there are any other differences in the SQL export file that you might want to take into consideration

Dump MySQL database with Qt

I have this slot:
void Managment::dbExportTriggered()
{
save = QFileDialog::getSaveFileName(this, trUtf8("Export db"),
QDir::currentPath() + "Backup/",
trUtf8("Dumped database (*.sql)"));
sqlQuery = "SELECT * INTO OUTFILE '" + save + ".sql' FROM Users, Data";
//QMessageBox::critical(0, trUtf8("query dump"), QString::number(query.exec(sqlQuery)));
query.exec(sqlQuery);
}
And I have this query:
sqlQuery = "SELECT * INTO OUTFILE " + save + " FROM Users, Data";
I execute normally but no dumped file appear, the backup directory has the right permission, the dumped database must be in client.
UPDATE:
After a search I found that the INTO OUTFILE query will dump database in the server not in the client as I was thought, so my question now how can I dump database in remote MySQL server, any quick methods with out any external tools like mysqldump client.
SELECT ... INTO OUTFILE creates a file on the MySQL server machine, with permissions matching whoever the MySQL server runs as. Unless you have root access on the MySQL server to retrieve the file that you're exporting, SELECT ... INTO OUTFILE is unlikely to do what you want.
In fact, I think I'd go so far as to say that if you're trying to use SELECT ... INTO OUTFILE from a GUI client, you're probably taking the wrong approach to your problem.
Just an idea: Another approach is to call mysqldump with QProcess. With some google-fu this seems to be an example:
..
if (allDatabases->isChecked()) {
arguments << "--all-databases";
} else {
arguments << "--databases";
foreach(QListWidgetItem *item, databasesList->selectedItems())
arguments << item->text();
}
proc->setReadChannel(QProcess::StandardOutput);
QApplication::setOverrideCursor(Qt::WaitCursor);
proc->start("mysqldump", arguments);
..
Thus, you can also add some parameters to dump only a specific table.
Edit:
Just note from the mysql doc on the SELECT ... INTO OUTFILE statement:
If you want to create the resulting
file on some other host than the
server host, you normally cannot use
SELECT ... INTO OUTFILE since there is
no way to write a path to the file
relative to the server host's file
system.
Thus you must roll your own, or you can use mysql -e as suggested by the above documentation.
Did you dump/print save to check it's valid? Does currentPath() return a trailung "/"?
Could there be difference between the path as seen by your client program and as (to be) seen by the server?
Does the user have the necessary privileges (file privilege for sure, maybe more)
Can't you get an error message from the log?
Are you getting any errors running the sql statement?
I notice that you're concatenating the filename into the SQL query without surrounding it by quotation marks. Your code will yield something like
SELECT * INTO OUTFILE /path/to/somewhere FROM Users, Data
but the MySQL documentation says it wants something like
SELECT * INTO OUTFILE '/path/to/somewhere' FROM Users, Data
Also keep the following in mind:
The file is created on the server host, so you must have the FILE privilege to use this syntax. file_name cannot be an existing file, which among other things prevents files such as /etc/passwd and database tables from being destroyed.
If you're looking on your client, you won't see the file there, even if the operation succeeds.