我有一个方法,使用preparedStatements
将数据插入我的SQL数据库。目前,天气数据已插入mydb.weather_data
。出于某种原因,我没有连接到我的数据库(没有任何连接错误),但实际上没有数据插入我的数据库。
我想知道问题是什么?下面的数字都是用于测试插入的虚拟数据。
我的五个列的type
分别为varChar(10)
和Int
,其余为四个。
private static void batchInsertRecordsIntoTable() throws SQLException{
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String insertTableSQL = "INSERT INTO `mydb`.`weather_data`"
+ "(`dateTime`,`hourlyTemp`,`dewPoint`,`windSpeed`,`relHum`) VALUES"
+ "(?,?,?,?,?)";
try{
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
dbConnection.setAutoCommit(false);
preparedStatement.setString(1, "1111111111"); // dateTime
preparedStatement.setInt(2, 12); // hourlyTemp
preparedStatement.setInt(3, 12); // dewPoint
preparedStatement.setInt(4, 12); //windSpped
preparedStatement.setInt(5, 12); //relHum
preparedStatement.addBatch();
preparedStatement.executeBatch();
dbConnection.commit();
System.out.println("Record was inserted into mydb weather_data");
}catch(SQLException e){
System.out.println(e.getMessage());
dbConnection.rollback();
}finally{
if(preparedStatement!=null){
preparedStatement.close();
}
if(dbConnection!=null){
dbConnection.close();
}
}
}
答案 0 :(得分:0)
试试这个:
private static void batchInsertRecordsIntoTable() throws SQLException{
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String insertTableSQL = "INSERT INTO mydb.weather_data"
+ "(dateTime,hourlyTemp,dewPoint,windSpeed,relHum) VALUES"
+ "(?,?,?,?,?)";
try{
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
dbConnection.setAutoCommit(false);
preparedStatement.setString(1, "1111111111"); // dateTime
preparedStatement.setInt(2, 12); // hourlyTemp
preparedStatement.setInt(3, 12); // dewPoint
preparedStatement.setInt(4, 12); //windSpped
preparedStatement.setInt(5, 12); //relHum
preparedStatement.executeUpdate();
dbConnection.commit();
System.out.println("Record was inserted into mydb weather_data");
}catch(SQLException e){
System.out.println(e.getMessage());
dbConnection.rollback();
}finally{
if(preparedStatement!=null){
preparedStatement.close();
}
if(dbConnection!=null){
dbConnection.close();
}
}
}