I am using a prepared statement to insert to my database. Some of the values im inserting are NULL as the matches are yet to be played, and so the score is NULL, NULL.
void insertFixtures(List<String[]> fixtures) throws SQLException {
String query = "REPLACE INTO games (team1_id, team2_id, score1, score2, created_at, winner) VALUES (? ,?, ?, ?, ?, ?)";
Connection con = DBConnector.connect();
PreparedStatement stmt = con.prepareStatement(query);
for (String[] s : fixtures) {
int winner;
stmt.setString(1, s[0]);
stmt.setString(2, s[1]);
String nullTest1 = s[2];
if (nullTest1 != null) {
stmt.setString(3, s[2]);
stmt.setString(4, s[3]);
stmt.setString(5, s[4]);
int score1 = Integer.parseInt(s[2]);
int score2 = Integer.parseInt(s[3]);
System.out.println(score1);
System.out.println(score2);
if (score1 > score2) {
winner = 1;
} else if (score2 > score1) {
winner = 2;
} else {
winner = 0;
}
String gameWinner = Integer.toString(winner);
stmt.setString(6, gameWinner);
} else {
System.out.println("empty");
stmt.setString(3, null);
stmt.setString(4, null);
stmt.setString(5, s[4]);
stmt.setString(6, null);
}
}
stmt.execute();
stmt.close();
con.close();
}
InsertFixtures takes the list string array and inserts these into my database using a for loop.
The problem i have is with:
if(nullTest1 != null ){
When i run this code in debug mode and set nullTest1 to equal null it skips over this and goes into the else statement. However, when i run it real time it goes into this if statement and has an issue with parseInt on a null value.
This is an example of the strings im trying to insert into my database:
Fixture 45 42 1 0 1554642300
Fixture 49 48 null null 0
Any help is useful.
Thanks
You should check null before parsing a String into Integer:
int score2 = s[3] != null ? Integer.parseInt(s[3]) : 0;
You need to decide what should be the value if s[3] is null. I have put 0 just for example purpose.
Related
I know this question has been asked many times here on stackoverflow, however I still can't pinpoint the exact reason on why my code is not working.
This is the query:
String QUERY = "INSERT INTO orders (user, product_id, final_price, key_id) VALUES (?, ?, ?, ?)";
Manually running the query using the same parameters that I use on my failing function works perfectly.
This is the preparedStatement:
// ...more code up here...
PreparedStatement preparedStatement = connectionManager.databaseConnection.prepareStatement(QUERY);
preparedStatement.setInt(1, user_id);
preparedStatement.setInt(2, product_id);
preparedStatement.setFloat(3, _finalprice);
// ...more code down there...
preparedStatement.setInt(4, _keyid);
The error I'm getting is the following:
java.sql.SQLException: Parameter index out of range (0 < 1 ).
I have several other INSERTs done with the same technique and they all work flawlessly, I'm starting to think that there is some problem with the mysqlconnector I'm using (mysql-connector-java-8.0.19).
Full code for context:
private static boolean assignProduct(int product_id, int user_id)
{
String QUERY = "INSERT INTO orders (user, product_id, final_price, key_id) VALUES (?, ?, ?, ?)";
float _finalprice = 0;
int _discount = 0;
int _keyid = 0;
if(product_id <= 0 || user_id <= 0) {return false;}
Product _p;
try {
_p = Product_utils.productByID(product_id);
if(_p != null)
{
_finalprice = _p.getPrice();
_discount = _p.getDiscount();
if(_discount > 0)
{
_finalprice = _finalprice - (_finalprice * _discount / 100);
}
}else { return false;}
PreparedStatement preparedStatement = connectionManager.databaseConnection.prepareStatement(QUERY);
preparedStatement.setInt(1, user_id);
preparedStatement.setInt(2, product_id);
preparedStatement.setFloat(3, _finalprice);
_keyid = retriveKey(product_id);
if(_keyid == 0) { return false; }
preparedStatement.setInt(4, _keyid);
if(preparedStatement.executeUpdate() == 1) {return true;} else {return false;}
} catch (SQLException e) { System.out.println(e.toString()); return false;}
}
Resolved by upgrading my mysql connector to 8.0.20
I am using a prepared statement to insert to my database. Some of the values im inserting are NULL as the matches are yet to be played, and so the score is NULL, NULL.
void insertFixtures(List<String[]> fixtures) throws SQLException{
String query = "REPLACE INTO games (team1_id, team2_id, score1, score2, created_at, winner) VALUES (? ,?, ?, ?, ?, ?)";
Connection con = DBConnector.connect();
PreparedStatement stmt = con.prepareStatement(query);
for (String[] s : fixtures) {
try{
stmt.setString(1,s[0]);
stmt.setString(2,s[1]);
Integer score1 = s[2] != null ? Integer.parseInt(s[2]) : null;
Integer score2 = s[3] != null ? Integer.parseInt(s[3]) : null;
stmt.setInt(3, score1);
stmt.setInt(4, score2);
stmt.setString(5,s[4]);
String date = s[4];
int winner;
int dateValue = Integer.parseInt(date);
if (score1 > score2 && dateValue != 0) {
winner = 1;
} else if (score2 > score1 && dateValue != 0) {
winner = 2;
} else if(dateValue != 0) {
winner = 0;
} else {
winner = 3;
}
String gameWinner = Integer.toString(winner);
} catch (NumberFormatException e) {
e.printStackTrace();
}
stmt.execute();
}
stmt.close();
con.close();
}
InsertFixtures takes the list string array and inserts these into my database using a for loop.
The problem i have is with:
This is the print stack trace of the NullPointerException i get.
java.lang.NumberFormatException: For input string: "null"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at footballresults.MashapeClient.insertFixtures(MashapeClient.java:130)
at footballresults.MashapeClient.main(MashapeClient.java:190)
at line 130 is the code:
Integer score1 = s[2] != null ? Integer.parseInt(s[2]) : null;
Here im trying to parse the string from the array as an integer, unless it equals null i want it to be inserted into the database as null. Because the dateValue is 0 for games played it shouldn't move into the winner if statements.
This is an example of the strings im trying to insert into my database:
Fixture 45 42 1 0 1554642300
Fixture 49 48 null null 0
Any help is useful.
Thanks
Every time I run this code it gives me an exhauset resultset error. Im not sure what Im doing wrong but Ive tried removing the .next(); code for either one or all resultsets and then the error given is the ResultSet next wasnt called.
Im not sure what Im doing wrong. Just curious what people might think the issue could be? Ive done similar earlier in my servlet code but only used 1 statement and then 1 prepared statement. This time Im using 2 statements and 1 prepared statement.
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
rs11.next();
ResultSet rs12 = stmt.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
rs12.next();
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
int olo1 = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)");
pstmt1.clearParameters();
pstmt1.setInt(1,olo);
pstmt1.setInt(2,olo1);
ResultSet rs1 = pstmt1.executeQuery();
rs1.next();
Some ideas on your code (in comments)
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
//Check if you HAVE a line here!
if(!rs11.next()) {
System.out.println("No Recipe Found");
}
//Use stmt1 - that's why you created it?!
ResultSet rs12 = stmt1.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
if(!rs12.next()) {
System.out.println("No Ingredient Found");
}
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
//Read Ingredient from rs12 -> that's where you selected it into
int olo1 = ((Number) rs12.getObject(1).intValue(); //convert resultset value to int
While this might point you into the right direction for solving the current issue, you should consider learning about clean code.
Consider this code making use of try-with-resource, refactored out some methods, using prepared statements.
//Replace exiting code
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
int recipieId = getRecipeId(con, opt1);
int ingredientId = getIngredientId(con, ingr1);
if(recipeId > 0 && ingredientId > 0) {
//Process result
insertRecLnk(con, recipeId, ingredientId);
} else {
System.out.println("No INSERT");
}
//Helper functions
protected int getRecipeId(Connection con, String rec) {
try(PreparedStatement st = con.prepareStatement("SELECT recipe_ID FROM GM_Recipes WHERE rec_name=?")) {
st.setString(1, rec);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Recipe Found");
return -1;
}
protected int getIngredientId(Connection con, String ing) {
try(PreparedStatement st = con.prepareStatement("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name=?")) {
st.setString(1, ing);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Ingredient Found");
return -1;
}
protected void insertRecLnk(Connection con, int rId, int iId) {
try(PreparedStatement ps = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)")) {
ps.setInt(1, rId);
ps.setInt(2, iId);
ps.executeUpdate();
} catch(SQLException e) {
e.printStackTrace();
}
}
What I've tried:
try
{
PreparedStatement pstat = con.prepareStatement("insert into student_info values (?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
pstat.setInt(1, Integer.parseInt(txtId.getText()));
pstat.setString(2, txtFName.getText());
pstat.setString(3, txtLName.getText());
pstat.setString(4, gender);
int result = pstat.executeUpdate();
if(result > 0)
{
JOptionPane.showMessageDialog(null,"Data Inserted Succesfully !!!");
txtId.setText("");
txtFName.setText("");
txtLName.setText("");
bg.clearSelection();
ResultSet rs = pstat.getGeneratedKeys();
int newId= -1;
if(rs != null && rs.next())
{
newId = rs.getInt(1);
txtId.setText(String.valueOf(newId));
}
}
}
What I want:
The new id to be displayed in the textbox
What doesn't happen:
The new id doesnt get displayed in textfield..
Make this changes to your code:
PreparedStatement pstat = con
.prepareStatement("insert into student_info (firstname,lastname,gender)
values (?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS); // omit id column
pstat.setString(1, txtFName.getText());
pstat.setString(2, txtLName.getText());
pstat.setString(3, gender);
int result = pstat.executeUpdate();
// now got fetch the generated id
How can I check if a particular table say table A is empty in hive.I need to store this as boolean value to a variable in my java code.I tried this
Statement stmt = con.createStatement();
stmt.execute("Select count(*) from "+tableName);
int ct = stmt.getUpdateCount();
logger.info("Hive Table count is " +ct);
if(ct > 0)
return false;
else
return true;
but this doesnot seem to work. Any suggestions ?
Try this:
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select count(*) from "+tableName);
int ct = rs.getInt(0);
logger.info("Hive Table count is " +ct);
if(ct > 0)
return false;
else
return true;
You can try it this way :
ResultSet resultSet;
resultSet = stmt.executeQuery("select * from "+tableName);
int count = 0;
while (resultSet.next()) {
count++;
}
if(count == 0) // Table is empty.