java - 在 Java 中读取 sql 文件和执行数据库插入时出现异常

标签 java mysql sqlite

从一个sql文件中,我尝试读取sql查询并使用以下java代码创建一个mysqlite数据库:

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;

public class ReadMySqlDump {

static String sep = System.getProperty("line.separator");

public  ReadMySqlDump(){
    try{
        String s = "";
        String buff="";
        ArrayList<String> creates = new ArrayList<String> ();
           ArrayList<String> inserts = new ArrayList<String> ();

        boolean createStart = false;
        String currentCreate = "";

        BufferedReader br = new BufferedReader(new FileReader("mydb.sql.sql"));
        while((buff=br.readLine()) != null){
            buff = buff.trim();
             if(buff.length() == 0)continue;
            if(buff.startsWith("/*"))continue;
             if(buff.startsWith("--"))continue;
            if(createStart && buff.startsWith(");")){
             //   System.out.println("before: " + currentCreate);
                currentCreate = currentCreate.trim();
                if(currentCreate.endsWith(","))currentCreate = currentCreate.substring(0, currentCreate.length()-1);

             //currentCreate = currentCreate.substring(0, currentCreate.length()-2);
               //  System.out.println("after: " + currentCreate);
                    currentCreate += " " + buff + sep;
                createStart = false;
                creates.add(currentCreate);
                currentCreate = "";
                continue;
            }
            if(createStart){
                currentCreate += " " + buff +sep;
                continue;
            }
            if(!createStart && buff.startsWith("CREATE")){
                createStart = true;
                currentCreate += buff + sep;
                continue;
            }


            if(buff.startsWith("INSERT")) {
                inserts.add(buff);
                continue;

            }



        }
        br.close();

        for(String ss: creates){
            System.out.println(ss);
        }

        System.out.println("");
          System.out.println("");

                for(String ss: inserts){
            System.out.println(ss);
        }


         Class.forName("org.sqlite.JDBC");
    Connection conn = DriverManager.getConnection("jdbc:sqlite:testNew5.db");
    Statement stat = conn.createStatement();
          for(String ss: creates){

              System.out.println("SQL command: " + ss);

            stat.executeUpdate(ss);
        }

      //  ResultSet rs = stat.executeQuery("select * from tbl_passion_attributes");
        //  while(rs.next()){

         // }

        for (String ss : inserts){

                      System.out.println("ss: " + ss);
            int n =  stat.executeUpdate(ss);

                      System.out.println("n: " + n);
        }
             conn.close();



    } catch(Exception ex){

        ex.printStackTrace();

    }


}

public static void main(String[] args) {

    new   ReadMySqlDump();
}


}

create 语句完美运行并且表已创建;但是当插入语句开始时,我遇到第一个 INSERT 语句本身的异常。以下是异常(exception)情况:

ss: INSERT INTO acos (created, modified, id, parent_id, model, foreign_key, alias, lft,  rght) VALUES
java.sql.SQLException: near "VALUES": syntax error
at org.sqlite.DB.throwex(DB.java:288)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:114)
at org.sqlite.Stmt.executeUpdate(Stmt.java:102)
at ReadMySqlDump.<init>(ReadMySqlDump.java:94)
at ReadMySqlDump.main(ReadMySqlDump.java:113)

以下是mydb.sql.sql的内容

begin;
-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jan 30, 2013 at 11:55 AM
-- Server version: 5.5.24-log
-- PHP Version: 5.3.13



/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: abc
--

-- --------------------------------------------------------

--
-- Table structure for table acos
--

CREATE TABLE IF NOT EXISTS acos (
created datetime NOT NULL,
modified datetime NOT NULL,
id integer NOT NULL ,
parent_id integer DEFAULT NULL,
model varchar(255) DEFAULT NULL,
foreign_key integer DEFAULT NULL,
alias varchar(255) DEFAULT NULL,
lft integer DEFAULT NULL,
rght integer DEFAULT NULL,
);

--
-- Dumping data for table acos
--

INSERT INTO acos (created, modified, id, parent_id, model, foreign_key, alias, lft,  rght) VALUES
('0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, NULL, NULL, NULL, 'controllers', 1, 1124),
('0000-00-00 00:00:00', '0000-00-00 00:00:00', 2, 1, NULL, NULL, 'Pages', 2, 15);

-- --------------------------------------------------------

--
-- Table structure for table aros
--

CREATE TABLE IF NOT EXISTS aros (
created datetime NOT NULL,
modified datetime NOT NULL,
id integer NOT NULL ,
parent_id integer DEFAULT NULL,
model varchar(255) DEFAULT NULL,
foreign_key integer DEFAULT NULL,
alias varchar(255) DEFAULT NULL,
lft integer DEFAULT NULL,
rght integer DEFAULT NULL
);

--
-- Dumping data for table aros
--

INSERT INTO aros (created, modified, id, parent_id, model, foreign_key, alias, lft,  rght) VALUES
('0000-00-00 00:00:00', '0000-00-00 00:00:00', 1, NULL, 'Group', 1, NULL, 1, 12),
('0000-00-00 00:00:00', '0000-00-00 00:00:00', 2, NULL, 'Group', 2, NULL, 13, 18);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
commit;

我使用 here 中的 jdbc jar

如果有人能帮助解决这个问题,我将不胜感激。

最佳答案

发送到服务器的 INSERT 语句似乎不完整,在 VALUES 之后被截断,而它应该包含文件中以下两行提供的数据。

您没有从文件中正确获取 INSERT 语句。对于 CREATE,一切顺利:您正在管理一个 currentCreate 标志并连接语句行。您没有为 INSERT 执行此操作:

if(buff.startsWith("INSERT")) {
    inserts.add(buff);
    continue;
}

在这里,您只需获取第一行(buffbr.readLine() 的结果),其余的将被忽略。

解决方案是对 INSERT 执行与 CREATE 相同的操作:当您看到 INSERT 时,连接后续行,直到看到语句完成,即该行以 ) 结尾;.

关于java - 在 Java 中读取 sql 文件和执行数据库插入时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14722607/

相关文章:

iOS sqlite 无法提交,没有事务处于事件状态

sqlite - 我如何将数据从 SQLite 检索到 VB6?

java - 如何从 FilteredList 中删除项目?

mysql - 确定表是否在 CASCADE 上有 DELETE

java为自定义数据结构创建迭代器

php - 从数据库中选择多个表

mysql - 如何在 sql 中编写子查询以映射字典值

java - 如果 session 为真,则将用户信息发送到下一个 Activity - android

java - 有没有办法使用 BeanUtils.copyProperties 将 Set 映射到 List?

java - 如何在 Java 中将 getRGB(x,y) 整数像素转换为 Color(r,g,b,a)?