Java Execute SQL script file to database

Source: Internet
Author: User

One way: Read the contents of the SQL script file directly and then pass it to SQL.

Code: Runsqlservice:

@AutowiredPrivateRunsqldao Runsqldao; /*** Read the contents of the file into SQL execution *@paramSQLPath The path to the SQL file: such as: d:/testproject/web/sql/script. SQL*/     Public voidRunsqlbyreadfilecontent (String SQLPath)throwsException {Try{String sqlstr=Readfilebylines (SQLPath); //System.out.println ("obtained text:" + sqlstr);            if(Sqlstr.length () > 0) {runsqldao.runsqlbysqlstr (SQLSTR); }        } Catch(Exception e) {e.printstacktrace (); Throwe; }    }        /*** Read files in behavioral units, often used to read line-oriented format files*/    PrivateString Readfilebylines (String filePath)throwsException {stringbuffer str=NewStringBuffer (); BufferedReader Reader=NULL; Try{Reader=NewBufferedReader (NewInputStreamReader (NewFileInputStream (FilePath), "UTF-8")); String tempstring=NULL; intline = 1; //read one line at a time until NULL is read to the end of the file             while((tempstring = Reader.readline ())! =NULL) {                //Show Line Numbers//System.out.println ("line" + Line + ":" + tempstring);Str= Str.append ("" +tempstring); Line++;        } reader.close (); } Catch(IOException e) {e.printstacktrace (); Throwe; } finally {            if(Reader! =NULL) {                Try{reader.close (); } Catch(IOException E1) {}}} returnstr.tostring (); }

Runsqldao:

    /**  @param sqlstr     */public void            Runsqlbysqlstr (String sqlstr) {        Map<String,Object> map=new Hashmap<string,object >();        Map.put ("Sqlstr", sqlstr);        Sqlsessiontemplate.selectlist ("Runsql.runsqlbysqlstr", map);    }

Sqlmap:

<mapper namespace= "RUNSQL" ><select id= "runsqlbysqlstr" parametertype= "map" ><! [Cdata[${sqlstr}]]></select></mapper>

This type of writing: only supports changes to the data (new, modified, deleted), and the SQL file content begins with begin and ends with end. You cannot update operations such as table field modifications.

mode two; use Scriptrunner

Code: Runsqlservice:

    /*** Execute SQL script file using Scriptrunner *@paramSQLPath The path to the SQL file: such as: d:/testproject/web/sql/script. SQL*/     Public voidRunsqlbyscriptrunner (String SQLPath)throwsException {Try{sqlsession sqlsession=sqlsessionfactory.opensession (); Connection Conn=sqlsession.getconnection (); Scriptrunner Runner=NewScriptrunner (conn); Runner.setescapeprocessing (false); Runner.setsendfullscript (true); Runner.runscript (NewInputStreamReader (NewFileInputStream (SQLPath), "UTF-8")); } Catch(Exception e) {e.printstacktrace (); Throwe; }    }

This type of writing: There can be only one row of SQL, which executes an SQL statement at a time, or it will be an error.

Method Three: Use Scriptutils
Code: Runsqlservice: (The following two ways: script. SQL and Runsqlservice in the same directory)

Method (1)

    /*** Execute SQL script file using Spring tool class*/     Public voidRunsqlbyspringutils ()throwsException {Try{sqlsession sqlsession=sqlsessionfactory.opensession (); Connection Conn=sqlsession.getconnection (); Classpathresource RC=NewClasspathresource ("script. Sql ", Runsqldao.class);        SCRIPTUTILS.EXECUTESQLSCRIPT (conn, RC); } Catch(Exception e) {e.printstacktrace (); Throwe; }    }

Method (2)

    /*** Execute SQL script file using Spring tool class*/     Public voidRunsqlbyspringutils ()throwsException {Try{sqlsession sqlsession=sqlsessionfactory.opensession (); Connection Conn=sqlsession.getconnection (); Classpathresource RC=NewClasspathresource ("script. Sql ", Runsqldao.class); Encodedresource er=NewEncodedresource (RC, "Utf-8");        SCRIPTUTILS.EXECUTESQLSCRIPT (conn, er); } Catch(Exception e) {e.printstacktrace (); Throwe; }    }

Method (1), script. The SQL file must be ANSI, otherwise the Chinese characters in the data are garbled.

Method (2) solves the problem of the method (1), perfect, like the small partners to take to enjoy it.

Article for my original, reproduced please indicate the source.

Java Execute SQL script file to database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.