简体   繁体   English

将文件读入Derby数据库

[英]Reading a File Into a Derby Database

This is my latest attempt to read a text file into a Netbeans Derby database. 这是我最近一次尝试将文本文件读入Netbeans Derby数据库的尝试。 The file contains 5 rows with each row containing 7 items delineated by commas. 该文件包含5行,每行包含7个用逗号分隔的项目。 The program runs without any errors but the database is not updated at all. 该程序运行没有任何错误,但是数据库根本没有更新。 I would appreciate any help in fixing this code. 修复此代码将对您有所帮助。

<% Connection connection = null;
PreparedStatement ps = null;

String urlanddatabasename = "jdbc:derby://localhost:1527/ProgramName

String userName = "root";
String password = "root";

Class.forName("org.apache.derby.jdbc.ClientDriver");
connection = DriverManager.getConnection(urlanddatabasename,userName,password);

try{
     String fileName = saveFile;
     File file = new File(fileName);
     Scanner inputStream = new Scanner(file);
     String[] array = new String[7];

     Statement statement = connection.createStatement();
     while(inputStream.hasNext()){//reads from the file until there are no items left
     String data = inputStream.next();
     array = data.split(",");
     String reportidString = array[0];

     String coursenameString = array[1];

     String tardiesString = array[2];

     String absencesString = array[3];

     String totalgradeString = array[4];

     String teachernameString = array[5];

     String schoolnameString = array[6];

     statement.executeUpdate("INSERT INTO report(reportid, coursename, tardies, absences, totalgrade, teachername, schoolname) values(reportidString, coursenameString,tardiesString, absencesString, totalgradeString, teachernameString, teachernameString, schoolnameString)");

                }
                inputStream.close();
            }catch(FileNotFoundException e){e.printStackTrace();}

        %>

It seems that you are using this code inside a JSP scriptlet. 看来您正在JSP scriptlet中使用此代码。 This is very bad style. 这是非常糟糕的风格。 Especially for code without any relation to the view representation. 特别是对于与视图表示没有任何关系的代码。

So the first thing you should do, is to create an ordinary Java class and put that code inside. 因此,您应该做的第一件事是创建一个普通的Java类并将该代码放入其中。 Then you will remark that Class.forName() throws a checked exception (ClassNotFoundException) and some other parts like DriverManager.getConnection() , connection.createStatement() and statement.executeUpdate() throw SQLException . 然后,您将标记Class.forName()抛出一个检查异常(ClassNotFoundException),而其他一些部分(如DriverManager.getConnection()connection.createStatement()statement.executeUpdate()抛出SQLException You shouldn't let the servlet container catch these exceptions. 您不应该让servlet容器捕获这些异常。

Then write a simple main() method to check if your code is working or even better a JUnit test. 然后编写一个简单的main()方法来检查您的代码是否正常运行,甚至可以更好地进行JUnit测试。

You declared a PreparedStatement variable but never used it. 您声明了PreparedStatement变量,但从未使用过它。 Instead later you used a simple Statement . 相反,您后来使用了一个简单的Statement The first one fits better here. 第一个更适合这里。 So use something like that: 因此,使用类似这样的内容:

ps = connection.prepareStatement("INSERT INTO "
     + "report(reportid, coursename, tardies, absences, totalgrade, teachername, schoolname) "
     + "values(?, ?, ?, ?, ?, ?, ?)");

Use the ? 使用? as a placeholder for the actual values. 作为实际值的占位符。

Then later you set the values. 然后,您设置值。 Beware that the prepared statement index begins at 1. After the execution of all SQL inserts, you should commit the transaction. 请注意,准备好的语句索引从1开始。在执行所有SQL插入之后,应提交事务。 In case of an exception use abort() . 如果发生异常,请使用abort()

while(inputStream.hasNext()){//reads from the file until there are no items left
  // ...
  ps.setString(1, reportidString);
  ps.setString(2, coursenameString);
  // ...
  ps.executeUpdate();
}
connection.commit();

Afterwards you should clean up and free the ressources. 之后,您应该清理并释放资源。 The best place is in a finally of a try block: 最好的地方是在try块的finally

} finally {
  try {
    ps.close();
  } catch(SQLException e) {
    e.printStackTrace();
  }
  try {
    connection.close();
  } catch(SQLException e) {
    e.printStackTrace();
  }
}

Some further considerations: 一些进一步的考虑:

If you really want to use plain JSP, then make use of the Front Controller pattern . 如果您真的想使用纯JSP,请使用Front Controller模式 So every request goes to the front controller servlet. 因此,每个请求都发送到前端控制器servlet。 There you decide what kind of action to execute and collect the data for the view. 在那里,您可以决定执行哪种操作并为视图收集数据。 In the end forward to a JSP to create the view. 最后转到JSP创建视图。 Inside the JSP you should not use any scriptlets. 在JSP内部,您不应使用任何脚本。

Consider to use a MVC framework like Struts or Spring MVC . 考虑使用诸如StrutsSpring MVC之类的MVC框架。 But the current standard is Java Server Faces which is more component based. 但是当前的标准是Java Server Faces ,它是基于组件的。

Use a connection pool for the database connection. 使用连接池进行数据库连接。

Use logging instead of System.out.println() or e.printStackTrace() 使用日志记录代替System.out.println()e.printStackTrace()

To efficiently insert larger files into the database use batch inserts . 为了有效地将较大的文件插入数据库,请使用批处理插入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM