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;
Related
I am trying to populate a list of integers relating to accounts in a database. However, when I populate it and return it, the list only shows one element. I believe it has to do with the ownList.add(owner.getId() being in the scope of the if. When I put that statement outside of the if statement in the for scope the list is null. How should I remedy this to return the full list of account Ids?
Here's my code for that method.
public List<Integer>getAllAccountIDs(List<Account>allAccounts) {
List<Integer>ownList=new ArrayList<>();
allAccounts=accDao.findAll();
try (Connection conn =ConnectionUtil.getConnection()){
String sql = "SELECT id FROM project0.accounts";
Statement stmt =conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
int accId;
allAccounts =accDao.findAll();
while (rs.next()) {
accId=rs.getInt("id");
Account owner=null;
for(int i=0; i <allAccounts.size();i++) {
if(allAccounts.get(i).getId()==accId) {
owner=allAccounts.get(i);
ownList.add(owner.getId());
}
return ownList;
}
}
}catch(SQLException e) {
e.printStackTrace();
System.out.println("NO ACCOUNT EXIST FOR OWNER id");
return null;
}
return null;
}
}
Your statement return ownList is inside for-loop. The function will do what you programmed, that is, return result after the first pass and just after adding the first record.
You might want to move return after for loop (or after while).
The isue is that you return after the first iteration of the nested for loop:
for(int i=0; i <allAccounts.size();i++) {
if(allAccounts.get(i).getId()==accId) {
owner=allAccounts.get(i);
ownList.add(owner.getId());
}
return ownList;
^^^^^^
}
Instead of appending a new item after satisfying the condition for allAccounts.size(), you add an item once and leave the function
You need to modify your function as follows:
public List < Integer > getAllAccountIDs(List < Account > allAccounts) {
List < Integer > ownList = new ArrayList < > ();
allAccounts = accDao.findAll();
try (Connection conn = ConnectionUtil.getConnection()) {
String sql = "SELECT id FROM project0.accounts";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
int accId;
allAccounts = accDao.findAll();
while (rs.next()) {
accId = rs.getInt("id");
Account owner = null;
for (int i = 0; i < allAccounts.size(); i++) {
if (allAccounts.get(i).getId() == accId) {
owner = allAccounts.get(i);
ownList.add(owner.getId());
}
}
}
return ownList;
} catch (SQLException e) {
e.printStackTrace();
System.out.println("NO ACCOUNT EXIST FOR OWNER id");
}
return null;
}
to make sure that the valid list is returned at the end of try block not after the first iteration of your for-loop.
I am tring to check whether a data is available or not in database table.if not it will insert the data. But in first button click it works perfectly. by when i try to click the button again with the same value it gets inserted into the table. please help someone
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
// TODO add your handling code here:
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
ArrayList<String> list = new ArrayList<>();
Object obj[] = null;
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cem?useSSL=false", "root", "123");
//here stu is database name, root is username and password
Statement stmt = con.createStatement();
String pn = "select gname from games where gname='" + jTextField1.getText() + "'";
ResultSet rsPn = stmt.executeQuery(pn);
System.out.println(rsPn.next());
if (rsPn.next() == false) {
String q = ("insert into games(gid,gname) values(NULL,'" + jTextField1.getText() + "')");
int i = 0;
i = stmt.executeUpdate(q);
if (i > 0) {
System.out.println("success");
list.add(jTextField1.getText());
obj = list.toArray();
model.addRow(obj);
} else {
System.out.println("stuck somewhere");
}
StudentDetails.details();
jTextField1.setForeground(Color.BLACK);
stmt.close();
con.close();
} else {
jTextField1.setForeground(Color.red);
System.out.println("Name Already exist");
}
} catch (SQLException ex) {
Logger.getLogger(InsertPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(InsertPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
You're calling next() twice:
System.out.println(rsPn.next());
if (rsPn.next() == false) {
The second call will return false even if there's a row already (though it should work once there are two or more rows). Use a variable instead:
boolean hasNext = rdPn.next();
System.out.println(hasNext);
if (!hasNext) {
(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;
}
I am trying to pass in a JTable object which has columns DiscountID and Name. I am basically trying to get a row of the first column which is selected in JTable A (a DiscountID) and upon this set data relating to this selected record in JTable B which is JTable5 in the rs.next() loop.
The problem I have now is that since initially int row = table.getSelectedRow(); I'm having to set it to 0 to avoid an IndexOutOfBoundsException but then when I run the program JTable B will show information correlating to the first record in JTable A without any selection of data by me. I don't want any information to be displayed at all in JTable B until I select a record from JTable A whilst also avoiding the IndexOutOfBoundsException. It will be much appreciated if anyone can help me to fix this I've been trying hard to find a solution.
Here is the code to my method:
public static ArrayList<FlexiBand> getFlexiBands(JTable table, JTable table2) {
ArrayList<FlexiBand> flexiband = new ArrayList<FlexiBand>();
try {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
con = DriverManager
.getConnection("jdbc:mysql://localhost:3306/abpp034?user=abpp034&password=120001772");
stmt = con
.prepareStatement("SELECT UpperBound, PercentageRate FROM FlexiBand WHERE DiscountID = ?");
int row = table.getSelectedRow();
if (row == -1) {
row = 0;
for (int x = 0; x < table2.getRowCount(); x++) {
table2.setValueAt("", x, 0);
table2.setValueAt("", x, 1);
}
}
System.out.println(row); // This is printing me 0 meaning that row is still 0
System.out.println(table.getValueAt(row, 0)); // This means that row will be equal to 0
// when it goes to the next line.
stmt.setObject(1, table.getValueAt(row, 0));
try {
rs = stmt.executeQuery();
int i = 0;
while (rs.next()) {
FlexiBand fb = new FlexiBand();
fb.setUpperBound(rs.getInt("UpperBound"));
fb.setPercentageRate(rs.getInt("PercentageRate"));
flexiband.add(fb);
}
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
System.out.println(se.getErrorCode());
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException se) {
System.out.println(se.getErrorCode());
}
}
if (con != null) {
try {
con.close();
} catch (SQLException se) {
System.out.println(se.getErrorCode());
}
}
}
} catch (SQLException ex) {
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
}
return flexiband;
}
Here is where I call the method:
public static void main(String[] args) {
DiscountGUIView dgv = new DiscountGUIView();
setDiscountNames("Fixed", dgv.getjComboBox2());
getFlexiBands(dgv.getjTable2(), dgv.getjTable5());
}
in the same class as the method.
Just do in this way. Check whether row is selected or not.
public static void main(String[] args) {
DiscountGUIView dgv = new DiscountGUIView();
setDiscountNames("Fixed", dgv.getjComboBox2());
ArrayList<FlexiBand> flexiband = null;
if (dgv.getjTable2().getSelectedRow != -1) {
flexiband = getFlexiBands(dgv.getjTable2(), dgv.getjTable5());
}
if (flexiband !=null) {
// user selected a row, do what ever you want to do
} else {
// nothing is selected
// skip other operations
}
}
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.