I am making an application for booking a movie ticket, then I want to make a button for selecting seat numbers by checking several conditions on the database.
I use JButton with the following actions:
private void A1ActionPerformed (java.awt.event.ActionEvent evt) {
try {
Object day = cmbHari.getSelectedItem ();
Object stud = cmbStud.getSelectedItem ();
String sql = "SELECT * FROM message where id_kursi = '" + A1.getText () + "' AND id_film = '" + txtIDFilm.getText () + "' AND start = '" + txtJam.getText () + "' AND day = '"+ day +"' AND studio = '"+ stud +"' ";
Stat statement = conn.createStatement ();
ResultSet result = stat.executeQuery (sql);
if (result.equals (true)) {
JOptionPane.showMessageDialog (null, "Seat has been booked");
} else {
JOptionPane.showMessageDialog (null, "Seat booked");
txtKur.setText ("A1");
}
} catch (SQLException ex) {
Logger.getLogger (belitiket.class.getName ()). Log (Level.SEVERE, null, ex);
}
}
But always the seats can be ordered even though all conditions are fulfilled, the seats should not be ordered.
EDIT:
Thanks guys, solved.
private void A1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Object hari = cmbHari.getSelectedItem();
String h=hari.toString();
Object stud = cmbStud.getSelectedItem();
String s=stud.toString();
String insert = "select 1 from pesan where id_kursi=? and id_film=? and mulai=? and hari=? and studio=?;";
PreparedStatement ps = conn.prepareStatement(insert);
ps.setString(1, A1.getText());
ps.setString(2, txtIDFilm.getText());
ps.setString(3, txtJam.getText());
ps.setString(4, h);
ps.setString(5, s);
ResultSet rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Kursi Sudah Dipesan");
txtKur.setText("");
}else{
JOptionPane.showMessageDialog(null, "Kursi Dipesan");
txtKur.setText("A1");
}
} catch (SQLException ex) {
Logger.getLogger(belitiket.class.getName()).log(Level.SEVERE, null, ex);
}
}
The ResultSet is an iterative item and not a boolean to be compared to.
Also if you don't need a result use SELECT 1 ... that way if there is an item there will be a result and it can be done quickly on the server rather than marshalling unneeded information.
Related
I am having a sql syntax issue when I am trying to update my databse through my update method which is trigured by a button
here is the button code
update.addActionListener(e -> {
int i = table.getSelectedRow();
if (i >= 0) {
model.setValueAt(PackId.getText(), i, 0);
model.setValueAt(PackName.getText(), i, 1);
model.setValueAt(VendorName.getText(), i, 2);
model.setValueAt(PackValue.getText(), i, 3);
try {
updatepacks(PackId,PackName,VendorName,PackValue);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} else {
System.out.println("Update Error");
}
The update method code
public void updatepacks(JTextField PackId, JTextField PackName, JTextField VendorName, JTextField PackValue) throws SQLException {
try{
Connection conn = DriverManager.getConnection("jdbc:sqlite:packsver3.db");
String sqlupdate = "Update packs" + " SET PackName = ?" + " VendorName = ?" + "PackValue = ? " + "Where PackId = ? ";
try (PreparedStatement ps = conn.prepareStatement(sqlupdate)) {
ps.setString(1, String.valueOf(PackId));
ps.setString(2, String.valueOf(PackName));
ps.setString(3, String.valueOf(VendorName));
ps.setString(4, String.valueOf(PackValue));
ps.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
}
}
And the error
You missed the commas in the UPDATE statement. It should look like:
String sqlupdate = "Update packs"
+ " SET PackName = ?, " // added comma at the end
+ " VendorName = ?, " // added comma at the end
+ "PackValue = ? "
+ "Where PackId = ? ";
I have a problem with line pstmt.setLong(1, id);. I get an error that the value is not set for the parameter number 1. If I use the String SQL without the question mark, it works. Also, when I use ARM the PreparedStatement and ResultSet are not automatically closed so I have to close them, and finally doesn't seem to work either
#Override
public Company getCompany(long id) {
Connection con = ConnectionPool.getInstance().getConnection();
String sql = "SELECT * FROM Company WHERE ID=?";
//String sql = "SELECT * FROM Company WHERE ID=" + id;
Company company = new Company();
try (
PreparedStatement pstmt = con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();)
{
pstmt.setLong(1, id);
if (rs.next()) {
company.setId(rs.getLong(1));
company.setCompName(rs.getString(2));
company.setPassword(rs.getString(3));
company.setEmail(rs.getString(4));
} else {
System.out.println("Company with ID: " + id + " could not be found\n");
}
pstmt.close();
rs.close();
} catch (SQLException e) {
CouponSystemException ex = new CouponSystemException("Company with ID: " + id + " could not be retrieved\n", e);
System.out.println(ex.getMessage());
System.out.println(e);
}
ConnectionPool.getInstance().returnConnection(con);
return company;
}
Set the parameter before executing the query.
Also, You don't need to close Statement and result sets defined in try-with-resource statements as they'll be closed automatically when you leave the try scope.
try(PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setLong(1, id);
try(ResultSet rs = pstmt.executeQuery()) {
// do stuff
}
}
You need to set the PreparedStatement's parameters before executing it. Also note that this you're using the try-with-resource syntax you shouldn't close the resources yourself:
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setLong(1, id);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
company.setId(rs.getLong(1));
company.setCompName(rs.getString(2));
company.setPassword(rs.getString(3));
company.setEmail(rs.getString(4));
} else {
System.out.println("Company with ID: " + id + " could not be found\n");
}
}
} catch (SQLException e) {
CouponSystemException ex = new CouponSystemException("Company with ID: " + id + " could not be retrieved\n", e);
System.out.println(ex.getMessage());
System.out.println(e);
}
I am currently writing a simple Java app that reads information from an XLS file and then enters it in the database. Since that XLS does have duplicated records, I do a simple check if the entry in the XLS file already exists in the database. Here is my code:
public static void addResult(ArrayList<ArrayList<String>> listResults)
{
try
{
openDatabase();
stmt = c.createStatement();
for (int i = 0; i < listResults.size(); i++)
{
PreparedStatement stm = c.prepareStatement("SELECT player_name FROM results WHERE player_name=?;");
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
System.out.println(stm);
ResultSet rs = stm.executeQuery();
if (rs.getRow() <= 0)
{
String typeOfPlay = new String();
if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Simple"))
{
typeOfPlay = "single";
}
else if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Double"))
{
typeOfPlay = "double";
}
stm = c.prepareStatement("INSERT INTO results (player_name, school_id, " + typeOfPlay + ", tournament_id) "
+ "VALUES(?,?,?,?);");
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
stm.setString(2, listResults.get(i).get(ReadResultsFile.SCHOOL_ID));
stm.setInt(3, Integer.parseInt(listResults.get(i).get(ReadResultsFile.SCORE)));
stm.setString(4, "1");
stm.executeUpdate();
}
else
{
String typeOfPlay = new String();
if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Simple"))
{
typeOfPlay = "single";
}
else if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Double"))
{
typeOfPlay = "double";
}
stm = c.prepareStatement("UPDATE results SET " + typeOfPlay + "=? WHERE player_name=?;");
stm.setString(1, typeOfPlay);
stm.setString(2, listResults.get(i).get(ReadResultsFile.SCORE));
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
System.out.println(stm);
stm.executeUpdate();
}
}
closeDatabase();
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
The problem that arises is that the rs.getRow() function always returns -1. I tried running the SELECT query directly in the database tool and the query returns the player_name column if there is already a similar entry existing. It unfortunately do the same in Java.
I am unsure what to do at this point.
Thank you for any hint!
getRow will not work as per the javadocs
Retrieves the current row number. The first row is number 1, the second number 2, and so on.
and
A ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row
Usually use
while (rs.next ()) {....
I'm trying to code a system for a large IRC channel (Twitch Channel)
One of the things I'm trying to do is log every user and give them points for being in the chat. For all intents and purposes the chat is just a large IRC channel. I'm retrieving the users in a big list from the twitch API, I put all the usernames in a large Array and running the following timer with a while loop:
timer = new Timer(900000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
updating = true;
try {
Arraynumber = 0;
TwitchBot.getDate();
arrayused = false;
System.out.println("trying to save users if theres enough stuff");
while(Arraynumber < TwitchBot.words.length){
TwitchBot.CheckUpdateUserSQL(TwitchBot.words[Arraynumber]);
Arraynumber++;
System.out.println("updating database");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
As you can see it's a simple timer that picks the name from a String[] and runs every name through the script individually.
The updateuser looks like such:
public static void CheckUpdateUserSQL(String sqluser) throws ClassNotFoundException{
selectSQL(sqluser);
if (id == "thisuserdoesntexistforsure"){
InsertSQL(sqluser);
}
else{
int progress = CurrentTime - lastlogin;
int totalprogress = progress + totaltime;
if(progress < 60 && progress > 0){
c15 = null;
Statement stmt = null;
if(isonline == 1) {
coins = progress / 4;
}
else{
coins = progress / 5;
}
int coinsincrease = (int) Math.ceil(coins);
int coinstotal = coinsamount + coinsincrease;
Class.forName("org.sqlite.JDBC");
try {
c15 = DriverManager.getConnection("jdbc:sqlite:users.db");
c15.setAutoCommit(false);
stmt = c15.createStatement();
String sql = "UPDATE USERS set TOTALTIME = " + totalprogress + " where NAME='" + sqluser + "';";
stmt.executeUpdate(sql);
c15.commit();
String sql2 = "UPDATE USERS set LASTLOGIN = " + CurrentTime + " where NAME='" + sqluser + "';";
stmt.executeUpdate(sql2);
c15.commit();
String sql3 = "UPDATE USERS set TOTALCOIN = " + coinstotal + " where NAME='" + sqluser + "';";
stmt.executeUpdate(sql3);
c15.commit();
String sql4 = "UPDATE USERS set ISONLINE = 0 where NAME='" + sqluser + "';";
stmt.executeUpdate(sql4);
c15.commit();
stmt.close();
c15.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
Connection c = null;
Statement stmt = null;
try {
c = DriverManager.getConnection("jdbc:sqlite:users.db");
c.setAutoCommit(false);
stmt = c.createStatement();
String sql2 = "UPDATE USERS set LASTLOGIN = " + CurrentTime + " where NAME='" + sqluser + "';";
stmt.executeUpdate(sql2);
c.commit();
stmt.close();
c15.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
This code checks whether an user exists. (using the select method, which is as concise as I can get it, it only search for an username and returns the id, which will be 'thisuderdoesntexistforsure' if nothing returns)
If the user exists it will run the code to calculate their online time and the increase in online time and points since the last time they visited. Then updates the code. If they were not online or if the time somehow returns a negative value (or one that's too high) it will instead only update the timestamp and skip the rest of the updates. This makes sure that users who leave for a day don't just get 1.400 minutes of online time when they log on five minutes the next day.
Anyway. My question is; How can I trim it down? I'm running into an issue where it will take 6 minutes to update the entire userlist. having 2000 users online is not rare and it would take 2,000 loops through that while loop to update them all. The program is updating more often then not. I've tried cutting down the code to be as condensed as possible, but I have no idea where to start to speed things up.
Sorry if I'm coming over as moronic, I'm relatively new to SQL and this is my biggest project yet in JAVA.
You can use batching to perform your updates, but in your given code a simpler optimization would be to update the values with one update call (instead of 4). Also, you could use PreparedStatement and try-with-resources close. Something like,
public static void CheckUpdateUserSQL(String sqluser) throws ClassNotFoundException {
selectSQL(sqluser);
if (id.equals("thisuserdoesntexistforsure")) {
InsertSQL(sqluser);
} else {
String sql = "UPDATE USERS set TOTALTIME = ?, LASTLOGIN = ?, "
+ "TOTALCOIN = ?, ISONLINE = 0 where NAME = ?";
String sql2 = "UPDATE USERS set LASTLOGIN = ? where NAME=?";
int progress = CurrentTime - lastlogin;
int totalprogress = progress + totaltime;
if (progress < 60 && progress > 0) {
if (isonline == 1) {
coins = progress / 4;
} else {
coins = progress / 5;
}
int coinsincrease = (int) Math.ceil(coins);
int coinstotal = coinsamount + coinsincrease;
Class.forName("org.sqlite.JDBC");
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:users.db");
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, totalprogress);
ps.setInt(2, CurrentTime);
ps.setInt(3, coinstotal);
ps.setString(4, sqluser);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
Class.forName("org.sqlite.JDBC");
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:users.db");
PreparedStatement ps = conn.prepareStatement(sql2)) {
ps.setInt(1, CurrentTime);
ps.setString(2, sqluser);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
What you need is batchupdate. Some good tutorial can be found on the internet.
An example can be the following:
stm = db.prepareStatement("INSERT INTO ITEM (ID, TYPE, TITEL, UITGELEEND) VALUES (?, ?, ?, ?)");
db.setAutoCommit(false);
for (int n = 0; n < ItemLijst.getItems().size(); n++) {
Item huidigItem = ItemLijst.getItemObvIdx(n);
stm.setString(1, huidigItem.getID().toString());
stm.setString(2, huidigItem.getType().toString());
stm.setString(3, huidigItem.getTitel());
stm.setString(4,String.valueOf(huidigItem.isUitgeleend()));
stm.addBatch();
}
String SQL = "UPDATE Employees SET age = 35 " +
"WHERE id = 100";
// Add above SQL statement in the batch.
stm.addBatch(SQL);
stm.executeBatch();
db.commit();
Also try avoiding joining strings, instead use '?', otherwise it will be subjected to sql injection attacks.
http://tutorials.jenkov.com/jdbc/batchupdate.html
http://www.tutorialspoint.com/jdbc/jdbc-batch-processing.htm
i have a swing application which consists of a text box and a button.On entering the emp_id and clicking the button it connects to mysql and fetch all the rows corresponding to the emp_id entered in a table. my code is fetching only 1 row of the mysql data, even though there is 3 rows corresponding to the emp_id
my code is:
try {
Class.forName(driverName);
Connection con = DriverManager.getConnection(url, userName,password);
String sql = "select * from devices where emp_id = " + textvalue;
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int i = 0;
if (rs.next()) {
asset_id = rs.getString("asset_id");
name = rs.getString("name");
project = rs.getString("project");
emp_id = rs.getString("emp_id");
emp_name = rs.getString("emp_name");
model.addRow(new Object[] { asset_id, name, project, emp_id,emp_name });
// i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error",JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(400, 300);
you are fetching only first row.. fetch it in a loop
while(rs.next())
{
asset_id = rs.getString("asset_id");
name = rs.getString("name");
project = rs.getString("project");
emp_id = rs.getString("emp_id");
emp_name=rs.getString("emp_name");
model.addRow(new Object[]{asset_id, name, project, emp_id,emp_name});
//i++;
}
You get only one row from ResultSet :
if (rs.next()) {
asset_id = rs.getString("asset_id");
name = rs.getString("name");
project = rs.getString("project");
emp_id = rs.getString("emp_id");
emp_name = rs.getString("emp_name");
model.addRow(new Object[] { asset_id, name, project, emp_id,
emp_name });
// i++;
}
replace if with while, for getting all rows in loop.
For centring frame use frame.setLocationRelativeTo(null);.
According to docs
If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen. The center point can be obtained with the GraphicsEnvironment.getCenterPoint method.
Also:
1) replace next code:
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
with System.out.println(i + " Record Found"); because its code duplication.
2)Don't use setSize(...) use pack() method.
3)Call frame1.setVisible(true); in last line of construction or like next:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.setVisible(true);
}
});