我使用MySQL,并决定写我自己的数据库辅助类,会给我类似于android的语法sql,但是,当我尝试执行更新语句使用PreparedStatement,当我运行代码时,数据库中不发生变化,但不会引发异常。我仔细检查了连接字符串,确保我的.jars是有序的,三重检查了我的语法,但没有任何结果。代码:java.sql.PreparedStatement.executeUpdate()不与MySQL数据库工作
DatabaseHelper.java:
public class DatabaseHelper {
String dbHost = "localhost";
String dbPort = "3306";
String dbName = "nakomangdb";
String dbUsername = "root";
String dbPassword = "sqldb";
String connectionString = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName;
Connection connection;
PreparedStatement preparedStatement;
public DatabaseHelper() {
}
public void closeDatabase() {
try {
if (!connection.isClosed())
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public void openDatabase() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionString, dbUsername, dbPassword);
connection.setAutoCommit(true);
} catch (ClassNotFoundException | SQLException ex) {
ex.printStackTrace();
}
}
public void update(String table, String[] set, Object[] to, String whereClause, Object[] whereArgs) {
StringBuilder sql = new StringBuilder("update ");
sql.append(table);
sql.append(" set ");
for (int i = 0; i < set.length; i++) {
sql.append(set[i]);
sql.append(" = ?");
if (i != (set.length - 1)) {
sql.append(", ");
}
}
sql.append(" ");
int argCount = to.length;
try {
if (whereClause != null) {
sql.append(whereClause);
sql.append(";");
preparedStatement = connection.prepareStatement(sql.toString());
for (Object s : whereArgs) {
preparedStatement.setObject(argCount++, s);
}
} else {
sql.append(";");
preparedStatement = connection.prepareStatement(sql.toString());
}
argCount = 0;
for (Object s : to) {
preparedStatement.setObject(argCount++, s);
}
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
长途区号:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DatabaseHelper dbHelper = new DatabaseHelper();
dbHelper.openDatabase();
dbHelper.update("customer",
new String[]{"fullName"},
new Object[]{"vernon"},
"where ID=?",
new Object[]{1});
dbHelper.closeDatabase();
response.getWriter().append("Done!");
}
你有没有检查你的服务器日志stacktrace? – DiogoSantana
我刚刚做了,我得到一个java.sql.SQLException:参数索引超出范围(0 <1),这是没有意义的,因为argCount从不从0,我检查,是否PreparedStatement.setXXX方法的顺序是所谓的问题?我是否必须严格按照该顺序设置参数1,2,3等等,或者我可以设置3,4,1,2? – BiGGZ
_“argCount永不为0”_ - 对不起,这是不正确的。 'argCount'初始化为零,'argCount ++'为***后***增量。 –