我需要动态更新数据库信息。我用过MySQL。这是我的代码:
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
static final String USER = "root";
static final String PASS = "";
/**
* @param args
*/
/**
* @param args
*/
public static void main(String[] args) {
Connection con = null;
PreparedStatement pstmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database....");
con = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
String psql;
psql = "Update Employees SET age = ? WHERE id = ?";
pstmt = con.prepareStatement(psql);
pstmt.setInt(1, 20);
pstmt.setInt(2, 100);
int prows = pstmt.executeUpdate(psql);
System.out.println("PRows impacted : " + prows);
psql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = pstmt.executeQuery(psql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
pstmt.close();
con.close();
} catch(SQLException se){
se.printStackTrace();
} catch(Exception e){
e.printStackTrace();
} finally{
try{
if(pstmt != null)
pstmt.close();
} catch (SQLException se2){
}
try{
if(con != null)
con.close();
} catch (SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
但我得到的SQL语法错误如下:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error
in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near '? WHERE id = ?' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486)
at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1552)
at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2607)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1480)
at Practice2.main(Practice2.java:39)
我已经google了解决方案。但没有得到任何结果。这有什么不对?