I have a sql query to select data integer
I want do a test about this data that I test data in column with number 10
If I have 10 in column so pass to 10--
I do loop for into while
The result is correct but it's repeated many times
This is my code
int vl=10;
boolean found = false;
try {
if (jComboBox6.getSelectedIndex()>-1){
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+getdb(), "", "");
stmt = conn.createStatement();
ResultSet res=stmt.executeQuery( "SELECT VLAN FROM tt ");
while(res.next()) {
for(vl=10;vl>1;vl--) {
if(Integer.parseInt(res.getString(1))==vl) {
System.out.print(vl);
found = true;
break;
}
if (!found) {
System.out.print("NO");
//found = false;
break;
}
}
}
res.close();
}
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Etat_lieu.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.print("NO")
this line will be printed every time there is no match in the for loop.
Update
Let's simplify the problem.
boolean found = false;
while(res.next()) {
int value = Integer.parseInt(res.getString(1));
if (value == 10) {
System.out.print(value);
found = true;
}
[..do something else..]
}
if(!found) {
System.out.print("NO");
}
I think it's not worth to put an inner loop for a simple range check.
Related
Here's my code
public List<String> getListItem() {
try {
PreparedStatement ps = Main.getPlugin().sql.getConnection().prepareStatement("SELECT Name FROM textures");
ResultSet rs = ps.executeQuery();
List<String> l = new ArrayList<>();
while(rs.next()) {
l.add(rs.getString("Name"));
return l;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
and this is how i call it
for (String a : utils.getListItem()) {
cs.sendMessage(a);
}
But it just show the first row. I have search for this for like 2 days and nothing make my code work. Please help me.
Place your return statement outside while loop. If you put return statement within while loop it will return the list after first iteration and skip remaining.
while(rs.next()) {
l.add(rs.getString("Name"));
}
return l;
I have it set up where I can save my object information to a SQL database using this block of code:
public boolean add(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if (aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
sqlStr.append("INSERT INTO ");
sqlStr.append(ORDER_TABLE);
sqlStr.append(" (firstName, lastName, size, cheese, sausage, ham, total)");
sqlStr.append(" VALUES (?,?,?,?,?,?,?)");
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString(), Statement.RETURN_GENERATED_KEYS);
statement.setString(1, aOrder.getFirstName());
statement.setString(2, aOrder.getLastName());
statement.setString(3, aOrder.getPizzaSize());
statement.setBoolean(4, aOrder.getCheese());
statement.setBoolean(5, aOrder.getSausage());
statement.setBoolean(6, aOrder.getHam());
statement.setDouble(7, aOrder.getTotal());
rowCount = statement.executeUpdate();
if (rowCount == 1) {
ResultSet rs = statement.getGeneratedKeys();
if(rs.next()) {
aOrder.setId(rs.getInt(1));
}
success = true;
}
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot save pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Insert", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
What I am trying to do is change the total variable with an update to the object on the server. I dont have an error right now popping up but nothing is changing in my objects information. Here is my code with the update block:
public boolean update(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement = null;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if(aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
//TODO create the SQL and prepared statements to update an order in the database
rowCount = aOrder.getId();
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET firstName = ?, lastName = ?, size = ?, cheese = ?, sausage = ?, ham = ?, total = ? WHERE id = ").append(rowCount);
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setString(1, aOrder.getFirstName());
statement.setString(2, aOrder.getLastName());
statement.setString(3, aOrder.getPizzaSize());
statement.setBoolean(4, aOrder.getCheese());
statement.setBoolean(5, aOrder.getSausage());
statement.setBoolean(6, aOrder.getHam());
statement.setDouble(7, aOrder.getTotal());
rowCount = statement.executeUpdate();
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot update pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Update", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
I have it set up that just the total variable will be changed by the time the update block of code will be ran. So I was trying to just call all the variables again in the hopes that it would change the total.
I get the same results with this update block of code:
public boolean update(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement = null;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if(aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
rowCount = aOrder.getId();
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET total = ? WHERE id = ").append(rowCount);
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setDouble(1, aOrder.getTotal());
rowCount = statement.executeUpdate();
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot update pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Update", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
I figured out my problem I had something elsewhere in my code blocking the update. This is the code that is working to update the mySQL database in this case:
try {
//TODO create the SQL and prepared statements to update an order in the database
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET total = ? WHERE id = ?");
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setDouble(1, aOrder.getTotal());
statement.setInt(2, aOrder.getId());
rowCount = statement.executeUpdate();
}
Note:
I have two columns (Name(primary key), Email(primary key))
I have inserted two rows.
The 1st row, where name=ema email=ema#gmail.com, and my 2nd row where name=ena email=fe.
Now, when I want to insert a new record it only checks with the 1st row and the checking works, but if I want to insert name=ena and email=something it does not check for the second row. Can someone please suggest to me how do I overcome this?
try
{
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/testing","root","");
//block of code to check user exists or not.
//Statement statement = connection.createStatement();
PreparedStatement Pstatement;
String query = "select Name,Email from detail";
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery() ;
if(rs.next())
{
//from database
String name_db1 = rs.getString("Name").trim(); //using trim removes all white spaces
String email_db2 = rs.getString("Email").trim();
//from user GUI
String entered_name = name.getText().trim(); //using trim removes all white spaces
String entered_email = email.getText().trim();
boolean valid = true;
if(entered_name.equals(""))
{
JOptionPane.showMessageDialog(null,"Enter name");
valid = false;
}
else if(name_db1.equals(entered_name))
{
JOptionPane.showMessageDialog(null,"Enter name taken");
name.setText(null);
valid = false;
}
else if(entered_email.equals(""))
{
JOptionPane.showMessageDialog(null,"Enter email");
valid = false;
}
else if(email_db2.equals(entered_email))
{
JOptionPane.showMessageDialog(null,"email taken");
email.setText(null);
valid = false;
}
else if(valid == true)
{
Pstatement=connection.prepareStatement("insert into detail values(?,?)");
//Specifying the values of preparestatement parameter
Pstatement.setString(1,name.getText());
Pstatement.setString(2,email.getText());
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null,"registration successful");
//x++;
}
}
else
{
//incase if the user click without filling up the fields
JOptionPane.showMessageDialog(null,"not yet registered");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
Finally, I have figured out the logic, I just need to create a separate query for both Name and Email. This way I can search more than two values :D. If there is any mistake please let me know.
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testing","root","");
//creating a query for Name
String query1 = "select Name, Email from detail where Name like '"+name.getText()+"'";
PreparedStatement statement1 = con.prepareStatement(query1);
//creating a query for Email
String query2 = "select Name, Email from detail where Email like '"+email.getText()+"'";
PreparedStatement statement2 = con.prepareStatement(query2);
ResultSet result1 = statement1.executeQuery(); //resultset for name
ResultSet result2 = statement2.executeQuery(); //resultset for email
//checking name exception
if (result1.next())
{
String dbasename=result1.getString("Name").toString().trim();
String enteredname=new String(name.getText().trim());
if(enteredname.equals(""))
{
JOptionPane.showMessageDialog(null, "enter name");//valid1 = false;
}
else if(dbasename.equals(enteredname))
{
JOptionPane.showMessageDialog(null, "name taken");//valid1 = false;
name.setText(null);
}
}
//checking email exception
else if(result2.next())
{
String dbaseemail=result2.getString("Email").toString().trim();
String enteredemail=new String(email.getText().trim());
if(enteredemail.equals(""))
{
JOptionPane.showMessageDialog(null, "enter email");//valid1 = false;
}
else if(dbaseemail.equals(enteredemail))
{
JOptionPane.showMessageDialog(null, "email taken");//valid1 = false;
email.setText(null);
}
}
//if no exception is detect exectute the below statement
else
{
PreparedStatement Pstatement=con.prepareStatement("insert into detail values(?,?)");
Pstatement.setString(1,name.getText());
Pstatement.setString(2,email.getText());
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null,"Registered Successfully");
}
statement1.close();
statement2.close();
con.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error during searching");
}
(Postgres 9.4) I have a simple query that returns the integer 4, I then capture that number and loop through an if statement and return an edited result. The answer should come out to be 4 min but I keep getting 4 weeks .For some reason this is not working for example this is my code
try {
Connection con = null;
ResultSet rs;
con=DB.getConnection();
// this fire returns as an Integer 4
PreparedStatement ps =con.prepareStatement("SELECT EXTRACT
(EPOCH FROM(last_reply-created_on)/60):: integer as fire from streams where id=65");
rs= ps.executeQuery();
while (rs.next()) {
// I then put this method through
System.err.println(difference(rs.getInt("fire")));
}
con.close();
return ok();
} catch (Exception e) {
System.err.println(e.getMessage());
}
private static String difference(Integer i) {
String id="";
if(i<60)
{
4 is obviously less than 60 but it is not working
id= i+ " min";
}
if(i>=60 && i<1440)
{
id=i+ " hrs";
}
if(i>=1441 && i<10080)
{
id=i+" days";
}
else
{
id=i+" weeks";
}
// returns as 4 date
return id;
}
I am using this System.err.println(difference(rs.getInt("fire"))); to track the results. How can I make this work or is there a better way to achieve this?
You have a bug in if-else statement. Try below one
try {
Connection con = null;
ResultSet rs;
con=DB.getConnection();
// this fire returns as an Integer 4
PreparedStatement ps =con.prepareStatement("SELECT EXTRACT
(EPOCH FROM(last_reply-created_on)/60):: integer as fire from streams where id=65");
rs= ps.executeQuery();
while (rs.next()) {
// I then put this method through
System.err.println(difference(rs.getInt("fire")));
}
con.close();
return ok();
} catch (Exception e) {
System.err.println(e.getMessage());
}
private static String difference(Integer i) {
String id="";
if(i<60)
{
4 is obviously less than 60 but it is not working
id= i+ " min";
}else if(i>=60 && i<1440)
{
id=i+ " hrs";
}else if(i>=1441 && i<10080)
{
id=i+" days";
}
else
{
id=i+" weeks";
}
// returns as 4 date
return id;
}
When referring to the stored procedure client get two Resultset. With the first all is well, but the second consists of 20 rows, client developers claim that the procedure returns about 1000.
Connect connectObject = new Connect();
Connection connectionToPool = null;
CallableStatement procedure = null;
ResultSet table = null;
int rowCounter;
SOATO answer = new SOATO();
int counter = 1;
try {
connectObject.init(POOL);
connectionToPool = connectObject.getConnection();
procedure = connectionToPool.prepareCall("{call procedure()}");
procedure.execute();
while (true) {
rowCounter = procedure.getUpdateCount();
if (rowCounter > 0) { // This is update counter
procedure.getMoreResults();
continue;
}
if (rowCounter == 0) { // DDL command or 0 updates
procedure.getMoreResults();
continue;
}
table = procedure.getResultSet(); // If we reached here, we have a
// set of data, or no more results
if (table != null) {
switch (counter) {
case 1: // Area tables
answer.areaDataHandler(table);
counter++;
break;
case 2: // Region tables
answer.regionDataHandler(table);
counter++;
break;
default:
break;
}
procedure.getMoreResults();
continue;
}
break; // No more results
}
} catch (SQLException e) {
e.toString();
} finally {
if (table != null) {
try {
table.close();
} catch (SQLException e) {
e.toString();
}
}
if (procedure != null) {
try {
procedure.close();
} catch (SQLException e) {
e.toString();
}
}
if (connectionToPool != null) {
connectObject.releaseConnection(connectionToPool);
}
}
return answer;
}
regionDataHandler() similar areaDataHandler()
public void areaDataHandler(ResultSet table) throws SQLException {
while (table.next()) {
Area temp = new Area();
temp.setKodobl(table.getInt("kodobl"));
temp.setNameobl(table.getString("nameobl"));
area.add(temp);
}
}
Database - MSSQL 2000
jdbc driver - jtds1.2.5
p.s.
Please do not judge strictly junior and sorry for bad english
Problem solved, it turned out went int overflow field.
Problem found through via extra logging and exception handling.
In my code is not checked exceptions.
So guys do not be so stupid as I correctly handle exceptions in your projects