Java:编写SQL语句 [英] Java: Writing SQL Statements
本文介绍了Java:编写SQL语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个一次性Java程序,以将CSV文件中的一堆行添加到MySQL数据库.是否有任何Java类/工具包可以帮助您解决此问题?某些东西会逃脱必要的字符等?(例如,准备好的语句)
I'm writing a one-time Java program to add a bunch of rows in a CSV file to a MySQL database. Are there any Java classes/toolkits to help with this? Something that will escape necessary characters, etc? (eg prepared statements)
或者我应该自己写语句,就像这样:
Or should I just write the statements myself, like this:
result += String.format(
"INSERT INTO node (type, language, title) VALUES (%s, %s, %s)",
node.get("type"), node.get("language"), node.get("title")
);
推荐答案
如果您使用的是JDBC,请使用PreparedStatement.此类将为您节省手动转义输入内容的麻烦.
If you're using JDBC, use a PreparedStatement. This class will save you the trouble of escaping your inputs manually.
代码基本上看起来像这样(完全是在内存中-希望我不要忽略某些东西):
The code will look basically like this (totally from memory -- hope I didn't overlook something):
String sql = "INSERT INTO node (type, language, title) VALUES (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
try
{
pstmt.setString(1, node.get("type"));
pstmt.setString(2, node.get("language"));
pstmt.setString(3, node.get("title"));
pstmt.executeUpdate();
}
finally
{
pstmt.close();
}
这篇关于Java:编写SQL语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文