将CSV导入Access的Java代码 [英] Java code to import CSV into Access

查看:42
本文介绍了将CSV导入Access的Java代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将下面的代码发布到Sun开发者论坛,因为我认为这是错误的(真正的错误是在代码被击中之前).我得到的回应之一说,这是行不通的,请将其丢弃.但这实际上是有效的.它可能不是最好的代码(我是Java的新手),但是它固有地存在错误"之处吗?

I posted the code below to the Sun developers forum since I thought it was erroring (the true error was before this code was even hit). One of the responses I got said it would not work and to throw it away. But it is actually working. It might not be the best code (I am new to Java) but is there something inherently "wrong" with it?

=============

=============

代码:

推荐答案

字面上的答案是否定的-代码从不存在任何天生错误",这取决于是否满足要求-可能包括也可能不包括可维护,安全,可靠或快速.

The literal answer is no - there is never anything "inherently wrong" with code, it's a matter of whether it meets the requirements - which may or may not include being maintainable, secure, robust or fast.

您正在运行的代码实际上是纯粹在Access中的一个JET查询-Java代码除了告诉Access运行查询之外,什么也不做.

The code you are running is actually a JET query purely within Access - the Java code is doing nothing except telling Access to run the query.

一方面,如果它没有损坏,请不要修复它.另一方面,它很有可能在不久的将来破裂,因此您可以尝试提前修复它.

On the one hand, if it ain't broke don't fix it. On the other hand, there's a good chance it will break in the near future so you could try fixing it in advance.

它可能断裂的两个可能原因是:

The two likely reasons it might break are:

  1. SQL注入风险.根据csvDirPath和csvFileName的来源(例如csvFileName可能来自用户上传的文件的名称?),以及Access JDBC驱动程序的巧妙程度,您可能会愿意通过插入分号(或一些用于创建子查询的括号)和一些附加的SQL命令到查询中.
  2. 您所依赖的CSV文件列与Access表的列兼容.如果您未选中要上传的CSV,或者CSV生成器具有处理null的特定方式,或者您一天有一种不寻常的日期或数字格式,则在插入Access表时可能会出错.

说了这么多,我们都在这里谈实用主义.如果上面的代码来自一个实用类,而您每周/每月/每年/曾经几次要使用它,那么这实际上不是问题.

Having said all that, we are all about pragmatism here. If the above code is from a utility class which you are going to use by hand a few times a week/month/year/ever, then it isn't really a problem.

如果这是构成Web应用程序一部分的类,则正式" Java方法是从CSV文件中读取记录(使用CSV解析器或CSV/文本JDBC驱动程序),从记录集中取出这些列,对其进行一些验证或健全性检查,然后使用新的PreparedStatement将它们插入Access数据库.麻烦更多了,但功能更强大了.

If it is a class which forms part of a web application, then the 'official' Java way to do it would be to read records out of the CSV file (either using a CSV parser or a CSV/text JDBC driver), get the columns out of the recordset, do some validation or sanity checking on them, and then use a new PreparedStatement to insert them into the Access database. Much more trouble but much more robust.

您可能会找到工具的组合(例如对象关系层或其他数据访问工具),这些工具可以为您做很多事情,但是设置工具和编写代码一样麻烦.再说一次,您将从任何一个中学到很多东西.

You can probably find a combination of tools (e.g. object-relational layers or other data access tools) which will do a lot of that for you, but setting up the tools is going to be as much hassle as writing the code. Then again, you'll learn a lot from either one.

这篇关于将CSV导入Access的Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆