I am looking for a way to escape strings for MySQL queries with Java.
But WAIT, before some of you jump straight away to the conclusion of "prepared statements", I wish to explain a little more.
The problem is, I don't have a MySQL connection. I am not executing any MySQL queries directly from Java. I don't know much about prepared statement, but AFAIK, prepared statements need a live connection to work.
我想让我的代码读入一堆 CSV/XLS 文件,获取数据,然后为 MySQL 生成一个巨大的 INSERT 查询。但是这个查询现在将存储在一个文本文件中。它不会执行,直到有人开绿灯并将此文本文件转储到数据库中。
有没有一种简单的方法可以在不使用矫枉过正的框架/库的情况下做到这一点?谢谢你们。
似乎没有任何现有的库/框架可以做这样的事情。所以我猜一个简单的String机械手可以吗?
class xxx {
private String escapeStringForMySQL(String s) {
return s.replaceAll("\\", "\\\\")
.replaceAll("\b","\\b")
.replaceAll("\n","\\n")
.replaceAll("\r", "\\r")
.replaceAll("\t", "\\t")
.replaceAll("\\x1A", "\\Z")
.replaceAll("\\x00", "\\0")
.replaceAll("'", "\\'")
.replaceAll("\"", "\\\"");
}
private String escapeWildcardsForMySQL(String s) {
return escapeStringForMySQL(s)
.replaceAll("%", "\\%")
.replaceAll("_","\\_");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6629 次 |
| 最近记录: |