how could i subtract a value based on the input on the text field directly to my database?
and how can i execute two queries at the same time i tried doing this but i had no luck
heres the code i am trying to execute
String sql1 = "select seat from passenger_details where seat = '"+seats+"'";
resultset = statement.executeQuery(sql1);
int count = 0;
while(resultset.next()) {
count = count + 1;
}
if(cc.equals("")||add.equals("")) {
JOptionPane.showMessageDialog(null,"Please Complete the form");
} else {
sql1 = "INSERT INTO passenger_details(fname,lname,gender,address,cc_no,bank_name,no_of_tickets,seat) VALUES('"+fnm+"','"+lnm+"','"+gnd+"','"+add+"','"+cc+"','"+bank+"','"+tckts+"','"+seats+"'),('"+fnm+"','"+lnm+"','"+gnd+"','"+add+"','"+cc+"','"+bank+"','"+tckts+"','"+seats2+"'),('"+fnm+"','"+lnm+"','"+gnd+"','"+add+"','"+cc+"','"+bank+"','"+tckts+"','"+seats3+"'),('"+fnm+"','"+lnm+"','"+gnd+"','"+add+"','"+cc+"','"+bank+"','"+tckts+"','"+seats4+"'),('"+fnm+"','"+lnm+"','"+gnd+"','"+add+"','"+cc+"','"+bank+"','"+tckts+"','"+seats5+"')";
String sql2 = "Update flight_details set seats_avail= seats_avail-'"+tckts+" Where route_name = '"+dest+"'";
statement.addBatch(sql1);
statement.addBatch(sql2);
statement.executeBatch();
JOptionPane.showMessageDialog(null,"Sucess");
}
Related
I am trying to update a database using input from user and saving it in jtable, then using jtable I am updating the database, but I am not able to get fetch and update 2nd row in database.
please suggest a solution, Thanks in advance.
try {
Class.forName("com.mysql.jdbc.Driver");
con = myconnection.getConnection();
String name;
for (int i = 0; i < jTable2.getRowCount(); i++) {
name = (String) jTable2.getModel().getValueAt(i, 0);
String abcd = "select * from medicine where Name=? ";
stmt = conn.prepareStatement(abcd);
stmt.setString(1, name);
rs = stmt.executeQuery();
if (rs.next()) {
name = (String) jTable2.getModel().getValueAt(i, 0);
String stock = rs.getString("qty");
int nowstock = Integer.parseInt(stock);
int qty1 = Integer.parseInt(jTable2.getValueAt(i, 2).toString());
int newstock = nowstock - qty1;//Integer.parseInt(jTable2.getValueAt(i, 2).toString());
String sqlupdate = "UPDATE medicine SET qty='" + newstock + "'WHERE Name='" + name + "' "; //
stmt = conn.prepareStatement(sqlupdate);
stmt.executeUpdate();
}
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Bill.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Bill.class.getName()).log(Level.SEVERE, null, ex);
}
The select serves no purpose, and you can just iterate all names and update directly:
for (int i=0; i < jTable2.getRowCount(); i++) {
String name = (String) jTable2.getModel().getValueAt(i, 0);
int qty1 = Integer.parseInt(jTable2.getValueAt(i, 2).toString());
String update = "UPDATE medicine SET qty = qty - ? WHERE Name = ?";
PreparedStatement ps = conn.prepareStatement(update);
ps.setInt(1, qty1);
ps.setString(2, name);
ps.executeUpdate();
}
If your JTable happens to have more than say 10 or so names, then a more efficient way to do this would be to use a single update with a WHERE IN clause containing all names which appear in the table, i.e.
UPDATE medicine SET qty = qty - ? WHERE Name IN (...);
I have a problem with a search form in a JSP project. In particular an user can subscribe to an event and the admin must be able to search all the members of that event.
I write a form like this:
out.println("<fieldset><legend>Search</legend><form action=\"cercaIscritti.jsp\" method=\"post\">"
+ "Name: <input name=\"name\" type=\"text\"><br>Surname: <input name=\"surname\" type=\"text\"><br>"
+ "Belonging: <input name=\"belonging\" type=\"text\"><br>Countr: <input name=\"country\" type=\"text\"><br>"
+ "<input type=\"submit\" value=\"Cerca\"></fieldset></form>");
(If it isn't readable: there are four <input>, one for each column in the table user and a <input> for submit).
I would like all the fields to be optional so that the admin can fill what it wants, but how do I build the query?
I tried something like this :
public ResultSet searchSubs(String name, String surname, String belonging, String country) {
try {
boolean n = false, s = false, b = false, c = false;
String query = "SELECT * FROM user WHERE ";
if (!isEmpty(name)) {
query += "firstName = ?";
n = true;
}
if (!isEmpty(surname)) {
if (n) {
query += " AND lastName = ?";
} else {
query += "lastName = ?";
}
s = true;
}
if (!isEmpty(belonging)) {
if (n || s) {
query += " AND belonging = ?";
} else {
query += "belonging = ?";
}
b = true;
}//and go on
But how can I add the values with the PreparedStatement? Is this the correct way? If it's not, how can I do something like that?
The booleans are there in the middle only for test, I thought I would use them in some way but I do not know how.
Here is a way you can follow to search with multiples values :
public ResultSet searchSubs(String name, String surname, String belonging, String country){
try {
String query = "SELECT * FROM user WHERE 1=1";
//---------------------------------------^^^
int index = 1;
if (!name.isEmpty()) {
query += " AND firstName = ?";
}
if (!surname.isEmpty()) {
query += " AND surname = ?";
}
if (!belonging.isEmpty()) {
query += " AND belonging = ?";
}
if (!country.isEmpty()) {
query += " AND country = ?";
}
PreparedStatement ps = connection.prepareStatement(query);
if (!name.isEmpty()) {
ps.setString(index++, name);
}
if (!surname.isEmpty()) {
ps.setString(index++, surname);
}
if (!belonging.isEmpty()) {
ps.setString(index++, belonging);
}
if (!country.isEmpty()) {
ps.setString(index++, country);
}
ResultSet rs = ps.executeQuery();
//...
The idea is simple :
In the Where clause use 1=1 to not get an error if the user not enter any value(in this case your query is SELECT * FROM user WHERE 1=1 and it will return every thing)
The first part if to fill the query with the non empty fields
The second if to fill the prepared statement with the right values.
finally execute the prepared statement and get the results.
How to make this one work? Obviously I don't know some very basic staff about SQL queries inside other SQL queries in Java but searching around didn't help!
Thank you in advance
try (Connection con = L2DatabaseFactory.getInstance().getConnection())
{
PreparedStatement stm = con.prepareStatement("SELECT count,owner_id FROM items WHERE item_id=57 order by count desc limit 10");
ResultSet rSet = stm.executeQuery();
while (rSet.next())
{
int owner_id = rSet.getInt("owner_id");
int count = rSet.getInt("count");
if (count == 0)
{
continue;
}
PreparedStatement stm1 = con.prepareStatement("SELECT char_name,accesslevel,online FROM characters WHERE obj_Id=" + owner_id);
ResultSet rSet1 = stm1.executeQuery();
while (rSet1.next())
{
int accessLevel = rSet.getInt("accesslevel");
if (accessLevel > 0)
{
continue;
}
String pl = rSet.getString("char_name");
int online = rSet.getInt("online");
String status = online == 1 ? "<font color=\"00FF00\">Online</font>" : "<font color=\"FF0000\">Offline</font>";
sb.append("<tr><td>"+ pl +"</td><td>"+ count +"</td><td>"+ status +"</td></tr>");
}
}
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Error", e);
}
It looks like you are trying to join two tables using Java code. This is not such a great idea and not good for performance. Let the database do the joins for you - it is an expert at that. Do not code "inner joins" in Java.
Apart from that: the prepared statements are not being closed and this will sooner or later cause you trouble with OS resources.
My suggestion would be to create one single query with an inner join or a select in statement and also close all prepared statements using try with resources. Something along these lines:
private String test() throws SQLException {
StringBuilder sb = new StringBuilder();
int count = 0;
try (Connection con = L2DatabaseFactory.getInstance().getConnection()) {
try (PreparedStatement stm1 = con.prepareStatement(
"SELECT char_name,accesslevel,online FROM characters WHERE obj_Id in (SELECT owner_id FROM items WHERE item_id=57 order by count desc limit 10)")) {
ResultSet rSet = stm1.executeQuery();
while (rSet.next()) {
count++;
int accessLevel = rSet.getInt("accesslevel");
if (accessLevel > 0) {
continue;
}
String pl = rSet.getString("char_name");
int online = rSet.getInt("online");
String status = online == 1 ? "<font color=\"00FF00\">Online</font>" : "<font color=\"FF0000\">Offline</font>";
sb.append("<tr><td>" + pl + "</td><td>" + count + "</td><td>" + status + "</td></tr>");
}
}
} catch (Exception e) {
Logger.getLogger("test").log(Level.SEVERE, "Error", e);
}
return sb.toString();
}
Facing performance issue while iterating through the ResultSet of an SQL query with cursor expressions.
SQL query(example)
select id, name , cursor (select id,name from subject ) as cusr1 from student
This is how I am retrieving the cursor in java
statement = connection.createStatement();
resultSet=statement.executeQuery(query);
while (resultSet.next()) { //Read every row
int columnCount = resultSet.getMetaData().getColumnCount();
for (int column = 1; column <= columnCount; column++) { //Read every column
String columnName = resultSet.getMetaData().getColumnName(column);
Object value = resultSet.getObject(columnName);
if (value != null) {
System.out.println("Value Not Null");
if(value instanceof ResultSet){
System.out.println("Success");
ResultSet rs1=(ResultSet)value;
while(rs1.next()){
String name=rs1.getString("name");
System.out.println("Name is "+name);
Long id=rs1.getLong("id");
System.out.println("Id is "+id);
}
}
}
}
}
The execution time of the query is very less compared to the processing time of the resultSet (iterating through the same ,getting the cusror data etc).
Am I doing anything wrong here?Is there any way to improve the performance?
I need to fill a Swing table with some data from MySQL DB. The problem is that the table does not display all the columns (i.e. a.aircraftType and b.aircraftCategory). In Debug mode I checked that the query returns correct data. So, why finally some columns are not displayed?
private JTable tbArrivals;
private QueryTableModelFS mdArrivals;
mdArrivals = new QueryTableModelFS();
tbArrivals = new JTable(mdArrivals);
private void fillArrivals() {
mdArrivals.setHost(url); mdArrivals.setDB(db); mdArrivals.setLogin(login); mdArrivals.setPassw(passw);
String query;
query = "SELECT a.id,a.flightNum_arr,a.from_ICAO,a.ETA,a.pkId,a.aircraftType,b.aircraftCategory " +
"FROM flightschedule a, aircrafts b " +
"WHERE a.aircraftType = b.aircraftType;";
mdArrivals.setQuery(query);
}
public void setQuery(String query) {
cache = new Vector();
try {
// Execute the query and store the result set and its metadata
Connection con = getConnection();
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
colCount = meta.getColumnCount();
// Rebuild the headers array with the new column names
headers = new String[colCount];
for (int h = 1; h <= colCount; h++) {
headers[h - 1] = meta.getColumnName(h);
}
while (rs.next()) {
String[] record = new String[colCount];
for (int i = 0; i < colCount; i++) {
record[i] = rs.getString(i + 1);
}
cache.addElement(record);
}
fireTableChanged(null);
rs.close();
if (con.getAutoCommit() != false) {
con.close();
}
} catch (Exception e) {
cache = new Vector();
e.printStackTrace();
}
}
I can't tell what how your TableModel works (it looks like you might be using the DefaultTableModel), but I would suggest using Vectors instead of Arrays to get the data from your ResultSet. Right now your code is very confusing. In one loop you are using (i - 1) to access the data. In the next loop you are using (i + 1). I know the reason is because Arrays are 0 based and the ResultSet is 1 based.
When you use a Vector your loops can just start with 1 and then you just use the addElement() method to add the data to the Vector so your code is not concerned with matching indexes.
See Table From Database Example in Table From Database.