[英]No data is getting inserted into my database using PreparedStatement
I have a method below that uses preparedStatements
to insert data into my SQL database. 我下面有一个使用preparedStatements
将数据插入我的SQL数据库的方法。 Currently it is weather data that gets inserted to mydb.weather_data
. 当前是天气数据插入到mydb.weather_data
。 For some reason, I have no trouble connecting to my database (not getting any connection errors), but no data actually get inserted into my DB. 由于某种原因,我可以很容易地连接到数据库(没有出现任何连接错误),但是实际上没有数据插入到数据库中。
I was wondering what the issue would be? 我想知道问题是什么? The numbers below are all dummy data to test insertion. 下面的数字都是要测试插入的伪数据。
The type
for my five columns are respectively varChar(10)
and Int
for the rest of the four. 我的五个列的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();
}
}
}
Try this: 尝试这个:
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.