Java – execute DB statements from files

I use embedded Apache Derby as my application I have one called CREATEDB SQL script of SQL, which creates all tables in the database and fills it with initial data, for example:

SET SCHEMA APP;


CREATE TABLE study (
    study_id    bigint  not null GENERATED ALWAYS AS IDENTITY  (START WITH 1,INCREMENT BY 1),name        varchar(50) not null,note         varchar(1000) DEFAULT '',created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,deleted boolean DEFAULT false,UNIQUE(name),CONSTRAINT primary_key PRIMARY KEY (study_id)

);

INSERT INTO "APP"."STUDY" (NAME) VALUES ('default');



CREATE TABLE img (
    img_id bigint not null GENERATED ALWAYS AS IDENTITY  (START WITH 1,filename varchar(200) not null,path        varchar(300) not null,flipped boolean DEFAULT false,type      smallint not null,note varchar(1000) DEFAULT '',PRIMARY KEY (img_id)    
);

ALTER TABLE img ADD COLUMN dpix integer DEFAULT -1;
ALTER TABLE img ADD COLUMN dpiy integer DEFAULT -1;

The question is how to load this file and execute all statements using Java? I'm trying different functions, but none of them work For example,

Statement s = conn.createStatement();
s.execute(sqlStr);

or

Statement s = conn.createStatement();
s.executeUpdate(sqlStr);

Where sqlstr is a string variable containing CREATEDB The contents of the SQL file How do I execute all the SQL commands included in the script to create all the tables and initialize them? By the way, the SQL script works because I use it in the squirrel SQL client to manually create and initialize the database Now I want to do this from my application

Solution

The following tutorial describes how to run a MySQL script (. SQL file) All you have to do is change the MySQL database connection to Derby dB and run it It will work

http://www.mkyong.com/jdbc/how-to-run-a-mysql-script-using-java/

This is another way to run MySQL scripts without using any third party libraries

http://coreyhulen.wordpress.com/2010/04/07/run-a-sql-script-for-mysql-using-java/

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>