我一直在研究一个连接到mysql数据库的java应用程序。我可以连接并运行查询,但是当我尝试获取一个字符串并将其作为sql查询运行时,出现此错误。
Exception in thread "main" 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 'INSERT INTO usageData (`COMID`,`Year`,`Month`,`kwhr`,`co2`)
VALUES ('15650', '2' at line 3
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2562)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1664)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1583)Bellow是我用来连接数据库的代码
public static void main(String[] args) throws Exception {
String dbms = "mysql";
String serverName = "localhost";
String portNumber = "8889";
String DBName = "ConnectDatabase";
String user = "root";
String password = "root";
ArrayList yearList = new ArrayList();
ArrayList customerRecordList = getCustomerRecords(args[0], yearList);
ArrayList climateRecordList = getClimateRecords(args[1]);
StringBuffer buf = new StringBuffer();
for (CustomerRecord record : customerRecordList) {
buf.append(customerRecord2SQL(record));
}
for (int i = (climateRecordList.size() - 1); i >= 0; i--) {
//for (ClimateRecord record : climateRecordList) {
ClimateRecord record = climateRecordList.get(i);
buf.append(climateRecord2SQL(record));
}
buf.append(cityStats(dbms,serverName,portNumber,DBName,user,password));
buf.append(zipStats(dbms,serverName,portNumber,DBName,user,password));
System.out.println(buf.toString());
//here is the code to go ahead and update the database
Connection con = null;
con = DriverManager.getConnection("jdbc:" + dbms + "://" + serverName + ":" + portNumber + "/" + DBName + "?user="+user+"&password=" + password);
Statement stmt = con.createStatement();
stmt.executeUpdate(buf.toString());
BufferedWriter out = new BufferedWriter(new FileWriter(args[2]));
out.write(buf.toString());
out.close();
}