Accepting NULL values and inserting in SQLite Java - java

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

Related

NumberFormatException because NULL not recognised on prepared statement Java

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.

Looping try/catch statement

I'm trying to take two random rowid from my database. Everything works but I have a scenario when there is only one rowid. I want to make a loop on my try/catch until there is second number in my database.
What I'm doing wrong? Thank you
public void Kaslaimejo() {
String sql = "SELECT rowid FROM Zaidejai WHERE Pirmas < 4 ORDER BY random() LIMIT 2";
Integer value1 = null, value2 = null;
Integer judesiukas1 = null, judesiukas2 = null;
int a = 0;
int k = 15; // kiek kartu? Reikia infinity padaryti
for (a = 0; a < 3; a++) {
try {
Connection conn = Serveris.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
if (rs.next()) {
value1 = rs.getInt("rowid");
if (rs.next()) {
value2 = rs.getInt("rowid");
PreparedStatement buvo = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo.setInt(1, i);
buvo.setInt(2, value1);
int buvolala = buvo.executeUpdate ();
PreparedStatement buvo2 = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo2.setInt(1, i);
buvo2.setInt(2, value2);
int buvolala2 = buvo2.executeUpdate ();//
i++;
}
System.out.println("Pirmas zaidejas" + value1); // atspausdina 1 random zaideja is duomenu bazes
System.out.println("Antras zaidejas" + value2); // atspausdina 2 random zaideja is duomenu bazes
}
} catch (SQLException e) {
a--;
//System.out.println(e.getMessage());
}
}
}
Right now my program loops two times and then gives me SQLException. How I can loop my program until there is no SQLException?
OK, I've tried to write what I think you're trying to do.
You wait for ever until someone puts at least two entries in the database.
You extract two values, process them, then wait some more.
Some points to watch out:
1. Object comparisons need to be made with .equals() not with ==
2. You might want to provide some way to break out of the infinite loop I've written (while(true)).
3. Careful with null values. They might produce NullPointerException.
4. Try to break up your code into methods. Each large block of code could go into each own method.
public void Kaslaimejo(){
String sql = "SELECT rowid FROM Zaidejai WHERE Pirmas < 4 ORDER BY random() LIMIT 2";
Integer judesiukas1 = null, judesiukas2 = null;
while(true) {
List<Integer> values = new ArrayList<>();
while (values.size() < 2) {
try (Connection conn = Serveris.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
if( rs.next() ){
Integer value = rs.getInt("rowid");
values.add(value);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
try( Connection conn = Serveris.connect()) {
PreparedStatement buvo = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo.setInt(1, i);
buvo.setInt(2, values.get(0));
int buvolala = buvo.executeUpdate ();
PreparedStatement buvo2 = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo2.setInt(1, i);
buvo2.setInt(2, values.get(1));
int buvolala2 = buvo2.executeUpdate ();//
i++;
}catch (SQLException e) {
e.printStackTrace();
}
Connection conn = Serveris.connect();
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT Pirmas FROM Zaidejai WHERE rowid = ?");
PreparedStatement pstmt2 = conn.prepareStatement("SELECT Pirmas FROM Zaidejai WHERE rowid = ?");
pstmt.setInt(1, values.get(0));
pstmt2.setInt(1, values.get(1));
ResultSet myrsv = pstmt.executeQuery();
ResultSet myrsv2 = pstmt2.executeQuery();
{
if (myrsv.next()) {
judesiukas1 = myrsv.getInt("Pirmas");
if (myrsv2.next()) {
judesiukas2 = myrsv2.getInt("Pirmas");
}
}
//System.out.println("Pirmo zaidejo veiksmas" + myrsv.getInt("Pirmas"));
//System.out.println("Antro zaidejo veiksmas" + myrsv2.getInt("Pirmas"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (judesiukas1.equals(judesiukas2)) // careful here. NullPointerException may happen.
{
try {
PreparedStatement laim = conn.prepareStatement("UPDATE Zaidejai SET Rezultatas = ? WHERE rowid = ?"); // ble ble update reikia naudoti , o ne insert into. Insert kai sukuriame nauja kazka tik
PreparedStatement laim2 = conn.prepareStatement("UPDATE Zaidejai SET Rezultatas = ? WHERE rowid = ?");
laim.setString(1, "Lygiosios");
laim.setInt(2, values.get(0));
laim2.setString(1, "Lygiosios");
laim2.setInt(2, values.get(1));
int irasyk = laim.executeUpdate (); // kodel executeupdate, o ne executequery????
int irasyk2 = laim2.executeUpdate (); // kodel executeupdate, o ne executequery????
{
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("Lygiosios");
} else {
// (1) - Rock
// (2) Scissors
// (3) - Paper
switch (values.get(0)){
case 1:
if (judesiukas2 == 2)
System.out.print("Zaidejas 1 wins!");
else
System.out.print("Zaidejas 2 wins!");
break;
case 2:
if (judesiukas2 == 3)
System.out.print("Zaidejas 1 wins!");
else
System.out.print("Zaidejas 2 wins!");
break;
case 3:
if (judesiukas2 == 1)
System.out.print("Zaidejas 1 wins!");
else
System.out.print("Zaidejas 2 wins!");
break;
}
}
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The logic becomes easier if you add the values to a list
var values = new ArrayList<Integer>();
while (values.Count < 2) {
try (Connection conn = Serveris.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql))
{
while (values.Count < 2 && rs.next()) {
Integer v = rs.getInt("rowid");
values.Add(v);
}
} catch (SQLException e) {
}
}
//TODO: process the values here
The advantage is, that you can retrieve one value at the first database query and the second at a later one or both in the same round and you don't have to keep track of which one of two variables to use.
(Bear with me with the syntax details, I'm not a Java programmer.)
How i can loop my program until there is no SQLException?
Change this (because, it will only allow to loop two times)
for (a = 0; a < 2; a++) {
to
while(true)
Put everything inside while(true), if exception occurred, then it will come out from the while loop. Something similar :
try
{
while(true)
{
...
...
}
...
}
catch(SQLException e)
{
// do somthing
}

Autonumber reset per day with Java Using Database

I build some software for my mini shop, I really confused with number queue customer who shop in my place. Please someone could help me.
I have a method which content with generate new number of queue from my customer. But when I open my Apps in the next day, I hope the queue is reset into 1 again.
My sytax Java like =
public void acak() {
try {
String generate = "SELECT COALESCE (MAX(no_antrian),0) AS kode from transaksi where tg_transaksi='" + tanggal + "'";
Statement stat = con.createStatement();
ResultSet res = stat.executeQuery(generate);
if (res.next()) {
try {
String kd_barang = res.getString("kode").substring(1);
String AN = "" + (Integer.parseInt(kd_barang) + 1);
String Nol = "";
if (AN.length() == 1) {
Nol = "000";
} else if (AN.length() == 2) {
Nol = "00";
} else if (AN.length() == 3) {
Nol = "0";
} else if (AN.length() == 4) {
Nol = "";
}
lblnoantrian.setText(Nol + AN);
} catch (NumberFormatException ex) {
System.out.println(ex.getMessage());
}
} else {
lblnoantrian.setText("0001");
}
} catch (Exception e) {
e.printStackTrace();
}
}
When I run this program in the next day, I see the eror like :
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
this eror's refers to:
String AN = "" + (Integer.parseInt(kd_barang) + 1);
maybe anyone can helping me..
this is not the proper use of COALESCE
as its description says
Returns the first non-NULL value in the list, or NULL if there are no non-NULL values.
mysql> SELECT COALESCE(NULL,1);
-> 1
mysql> SELECT COALESCE(NULL,NULL,NULL);
-> NULL
in case there is a empty string so its output would be empty string check
SELECT COALESCE (MAX(NULL),0)
->0
SELECT COALESCE (MAX(''),0)
->
SELECT COALESCE ('',0)
->
as you can see the last two queries returns empty string
replace your query with this query i hope this will work
SELECT
CASE
WHEN COALESCE (MAX(no_antrian), 0) = ''
THEN 0
ELSE COALESCE(MAX(no_antrian), 0)
END AS kodec
FROM
transaksi
WHERE tg_transaksi = '" + tanggal + "' "

Dynamic Sql qyery using prepare statement

Hii i want to create a dynamic query for filtering products. I want filter product from PRODUCTS table
on the basis of certain parameters like
Brand
Flavour
Price
Size
Type
i am creating a function in which i am executing MySQL query i want to check which parameter user has used which parameter is used those value will not be null and rest of the not selected parameters will be null. so i am checking the function which is null which is not and passing them in query
I have tried the following code
but it shows null pointer execption with following message
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 '' at line 1
and u tried printing the query:
SELECT * FROM products WHERE 1=1 AND brand in (?,? AND Price < ? AND Size < ? AND Type = ?
Follwing is the code:
public List<Products> Filter_Itemsl(String[] Brand, String[] Flavour, float Price, float Size, String Type) {
List<Object> parameters = new ArrayList<Object>();
ResultSet rs;
List<Products> data = null;
PreparedStatement stmt;
try {
StringBuilder query = new StringBuilder("SELECT * FROM products WHERE 1=1");
if (Brand != null) {
query.append(" AND brand in (");
for (int i = 0; i < Brand.length; i++) {
query.append('?');
if (i < Brand.length - 1) {
query.append(',');
}
parameters.add(Brand[i]);
}
}
if (Flavour != null) {
query.append(" AND Flavour in (");
for (int i = 0; i < Brand.length; i++) {
query.append('?');
if (i < Flavour.length - 1) {
query.append(',');
}
parameters.add(Flavour[i]);
}
}
if (Price != 0) {
query.append(" AND Price < ?");
parameters.add(Price);
}
if (Size != 0) {
query.append(" AND Size < ?");
parameters.add(Size);
}
if (Type != null) {
query.append(" AND Type = ?");
parameters.add(Type);
}
String Query = query.toString();
System.out.println(Query);
stmt = DataBaseConnection.DBConn.getConnection().prepareStatement(Query);
int i = 1;
for (Object parameter : parameters) {
stmt.setObject(i++, parameter);
}
rs = stmt.executeQuery();
if (rs != null) {
data = new ArrayList<Products>();
while (rs.next()) {
Products p = new Products();
p.setTitle(rs.getString("Ttile"));
p.setCategory(rs.getString("Category"));
p.setSubCategory(rs.getString("SubCategory"));
p.setSubCategoryTwo(rs.getString("SubCategorytwo"));
p.setPrice(rs.getInt("Price"));
p.setFlavour(rs.getString("Flavour"));
p.setSize(rs.getFloat("Size"));
p.setImage(rs.getString("image"));
p.setBrand(rs.getString("Brand"));
p.setInstock(rs.getString("instock"));
p.setInstockQty(rs.getInt("instockqty"));
p.setType(rs.getString("Type"));
data.add(p);
}
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
System.out.println("----------------------");
System.out.println(e.getMessage());
System.out.println("----------------------");
System.out.println(e.getSuppressed());
System.out.println("----------------------");
e.printStackTrace();
return null;
}
return data;
}
You are missing the closing ) for every IN sql statement.
You need to close the bracket after the for loop
if (Flavour != null) {
query.append(" AND Flavour in (");
for (int i = 0; i < Brand.length; i++) {
query.append('?');
if (i < Flavour.length - 1) {
query.append(',');
}
parameters.add(Flavour[i]);
}
query.append(")");
}

stop the code from getting executed after a jconformation dialog is closed with cancel option

I am trying to conform some message with the user and if he sayes he is sure the code written should execute but if he refuses the jconformation box the code should not be executed in my case even if i cancel or press no the code still gets executed and the data gets committed. what can i do to stop this my code is given below...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource()==jButton1){
JOptionPane.showConfirmDialog(rootPane, "Are You Sure You Want to Submit This Data and Genertate a New Remittance Id!");
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement("INSERT INTO dbo.bk_det(rm_id,bk_name,bk_branch,bk_add,bk_ref,ref_dt) VALUES (?,?,?,?,?,?)");
String rm = (tf_rm_id.getText().trim() == null || tf_rm_id.getText().equals("")) ? "0" : tf_rm_id.getText();
Object bkn = (cb_bkname.getSelectedItem() == null || cb_bkname.getSelectedItem().equals("")) ? "NILL" : cb_bkname.getSelectedItem();
Object bkbn = (cb_brname.getSelectedItem() == null || cb_brname.getSelectedItem().equals("")) ? "NILL" : cb_brname.getSelectedItem();
Object bkpln = (cb_plname.getSelectedItem() == null || cb_plname.getSelectedItem().equals("")) ? "NILL" : cb_plname.getSelectedItem();
String rf = (tb_bkref.getText().trim() == null || tb_bkref.getText().equals("")) ? "NILL" : tb_bkref.getText();
String rfdt = (tf_refdt.getText().trim() == null || tf_refdt.getText().equals("")) ? "NILL" : tf_refdt.getText();
stmt.setString(1, ""+(rm));
stmt.setString(2, ""+(bkn));
stmt.setString(3, ""+(bkbn));
stmt.setString(4, ""+(bkpln));
stmt.setString(5, ""+(rf));
stmt.setString(6, ""+(rfdt));
stmt.execute();
PreparedStatement stmt2 = con.prepareStatement("INSERT INTO bk_rep(rm_id, br_name, br_desig, br_pf, dt_rep, mob) VALUES (?,?,?,?,?,?)");
String rm1 = (tf_rm_id.getText().trim() == null || tf_rm_id.getText().equals("")) ? "0" : tf_rm_id.getText();
String brn = (tfbrname.getText().trim() == null || tfbrname.getText().equals("")) ? "NILL" : tfbrname.getText();
String brpf = (tf_brpf.getText().trim() == null || tf_brpf.getText().equals("")) ? "NILL" : tf_brpf.getText();
String brdes = (tf_brdes.getText().trim() == null || tf_brdes.getText().equals("")) ? "NILL" : tf_brdes.getText();
String brdtrep = (tf_rm_dt.getText().trim() == null || tf_rm_dt.getText().equals("")) ? "NILL" : tf_rm_dt.getText();
String brmob = (tf_brmob.getText().trim() == null || tf_brmob.getText().equals("")) ? "NILL" : tf_brmob.getText();
stmt2.setString(1, ""+(rm1));
stmt2.setString(2, ""+(brn));
stmt2.setString(3, ""+(brdes));
stmt2.setString(4, ""+(brpf));
stmt2.setString(5, ""+(brdtrep));
stmt2.setString(6, ""+(brmob));
stmt2.execute();
PreparedStatement stmt3 = con.prepareStatement("INSERT INTO bk_sec([bs_name],[bs_desig],[rm_id],[dt_rep]) VALUES (?,?,?,?)");
String rm2 = (tf_rm_id.getText().trim() == null || tf_rm_id.getText().equals("")) ? "0" : tf_rm_id.getText();
String sn = (tfsname.getText().trim() == null || tfsname.getText().equals("")) ? "NILL" : tfsname.getText();
String sdes = (tf_sdes.getText().trim() == null || tf_sdes.getText().equals("")) ? "NILL" : tf_sdes.getText();
String bsdtrep = (tf_rm_dt.getText().trim() == null || tf_rm_dt.getText().equals("")) ? "NILL" : tf_rm_dt.getText();
stmt3.setString(1, ""+(sn));
stmt3.setString(2, ""+(sdes));
stmt3.setString(3, ""+(rm2));
stmt3.setString(4, ""+(bsdtrep));
stmt3.execute();
JOptionPane.showMessageDialog(null, "COMMITED SUCCESSFULLY!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
CalendarUtil cal=new CalendarUtil();
tf_rm_id.setText(cal.getRemId());
String datePrefix = new SimpleDateFormat("MMMM dd, YYYY").format(new Date());
tf_rm_dt.setText(datePrefix);
tb_bkref.setText("");
tf_refdt.setText("");
tf_brpf.setText("");
tf_brdes.setText("");
tf_brmob.setText("");
tfsname.setText("");
tf_sdes.setText("");
tfbrname.setText("");
tf_scity.setText("");
}
}
if you would have a closer look to the showConfirmDialog, you would have seen it is returning an Integer. i will quote the API for the return.
Returns:
an integer indicating the option selected by the user
the return should be the order of the Buttons, you got in the confirm dialog, so it should be 2 in your case.
You just need to have an if statement now, which checks this value
you can do it like this:
int buffer = JOptionPane.showConfirmDialog(rootPane, "Are You Sure You Want to Submit This Data and Genertate a New Remittance Id!")
// user pressed yes
if(buffer == 0) {
try {
// whatever
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
else if(buffer == 1) {
// user input = no
}
else if(buffer == 2) {
// user input = cancel
}

Categories