SQL select won't show the selected item - java

When I run this code, why am I getting the last added record when selecting, and not the item from the box I selected?
String subj = null;
String sec = null;
String fac = null;
try {
String tmp=(String) secCombo.getSelectedItem();
String sql="select faculty,section,subject from facload where section=?";
pst=(PreparedStatement) conn.prepareStatement(sql);
pst.setString(1,tmp);
rs=pst.executeQuery();
while(rs.next()){
sec = rs.getString("section");
subj = rs.getString("subject");
fac = rs.getString("faculty");
}
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
JOptionPane.showMessageDialog(null, "prof " +fac + "\n" + "subject " + subj);
if (subCombo1.getSelectedItem().equals(fac) && subCombo.getSelectedItem().equals(subj)) {
JOptionPane.showMessageDialog(null, "lalalala");
}

Here:
while(rs.next()){
sec = rs.getString("section");
subj = rs.getString("subject");
fac = rs.getString("faculty");
}
You are assigning the same variables again and again in your loop. After the loop finishes, they have whatever values they were set to in the last iteration.

Related

Android :java.sql.SQLException: No current row in the ResultSet

I am getting the following error when i try to execute my query(s),but i don't know why it gives me the following error every time i try to execute my query(s).The error also appears in my logcat and not in a toast as i expected.
here is my code!!
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy/mm/dd");
String formattedDate = df.format(c);
System.out.println("it isssssssssssssssssssssssssssssssssssssssssaaaaaaaaaaaaaaaaaaaa"+getIntent().getStringExtra("nameid"));
String query = "Insert into CustomerSupportChat values('" + formattedDate + "','" + themsg.getText().toString() + "','Customer','3','"+getIntent().getStringExtra("nameid")+"','1','1') " +
"Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,Users_Login_Data.Username,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
"CustomerSupportChat INNER JOIN Users_Login_Data ON " +
"CustomerSupportChat.CustomerID = Users_Login_Data.CustomerID INNER JOIN StoresData ON " +
"CustomerSupportChat.StoreID = StoresData.StoreID";
String query2 =
"Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,Users_Login_Data.Username,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
"CustomerSupportChat INNER JOIN Users_Login_Data ON " +
"CustomerSupportChat.CustomerID = Users_Login_Data.CustomerID INNER JOIN StoresData ON " +
"CustomerSupportChat.StoreID = StoresData.StoreID Where SenderType = 'Store'";
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSet rs2 = stmt2.executeQuery(query2);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListChat(rs.getString("MessageDate"), rs.getString("MessageText"), rs.getString("SenderType"), rs2.getString("MessageText")));
themsg.setText("");
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
I have tried removing while and replacing it with if statement but it showed me the same error.
I also tried my query on mssql and it executed successfully.
EDIT I solved it by changing the date format to MM/dd/yyyy.
But now i get the following error:
java.sql.SQLException: No current row in the ResultSet.
Any ideas?
Looks like there is no null check for rs2 in the below line so could throw that error:
itemArrayList.add(new ClassListChat(rs.getString("MessageDate"), rs.getString("MessageText"), rs.getString("SenderType"), rs2.getString("MessageText")));
Also a better way to check for ResultSet not returning anything is like this:
if (rs.next() == false){
msg = "No Data found!";
success = false;
} else {
do {
// add items to itemArraylist...
} while (rs.next());
}
Read more: https://javarevisited.blogspot.com/2016/10/how-to-check-if-resultset-is-empty-in-Java-JDBC.html#ixzz6KIFZZHNB

Java printing database records on separate lines

I have a JDBC program that takes records from a MySQL database and prints out the results. The user can select which results they want from the database by selecting different checkboxes to only display certain results.
Here is the method which gets the records and prints them out:
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
String result = "";
while (rs.next()) {
if (cb1.isSelected()) {
int custid = rs.getInt("custid");
result += custid + " ";
}
if (cb2.isSelected()) {
String name = rs.getString("name");
result += name + " ";
}
if (cb3.isSelected()) {
String address = rs.getString("address");
result += address + " ";
}
if (cb4.isSelected()) {
String city = rs.getString("city");
result += city + " ";
}
if (cb5.isSelected()) {
String state = rs.getString("state");
result += state + " ";
}
if (cb6.isSelected()) {
int zip = rs.getInt("zip");
result += zip + " ";
}
// print the results
}
System.out.println(result);
results.setText(result);
stmt.close();
}
Currently, if I were to select say the first three checkboxes, I would get the output:
1 Smith, Tim 12 Elm St 2 Jones, Tom 435 Oak Dr 3 Avery, Bill 623 Ash Ave 4 Kerr, Debra 1573 Yew Crt
However, the output I am after is:
1, Smith, Tim, 12 Elm St
2, Jones, Tom, 435 Oak Dr
3, Avery, Bill, 623 Ash Ave
4, Kerr, Debra, 1573 Yew Crt
Is there any way I can add a new line after each record in the database, as well as maybe the commas in between items in each record? I am new to JDBC and MySQL connectivity, so any help or tips is appreciated.
You can print every single result just before the end of while loop, then it'll print every record in new line.
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
String result = "";
String singleResult = "";
while (rs.next()) {
if (cb1.isSelected()) {
int custid = rs.getInt("custid");
singleResult += custid + " ";
}
if (cb2.isSelected()) {
String name = rs.getString("name");
singleResult += name + " ";
}
if (cb3.isSelected()) {
String address = rs.getString("address");
singleResult += address + " ";
}
if (cb4.isSelected()) {
String city = rs.getString("city");
singleResult += city + " ";
}
if (cb5.isSelected()) {
String state = rs.getString("state");
singleResult += state + " ";
}
if (cb6.isSelected()) {
int zip = rs.getInt("zip");
singleResult += zip + " ";
}
System.out.println(singleResult);
result +=singleResult;
}
//System.out.println(result);
results.setText(result);
stmt.close();
}
Or you can append line separator, just before closing while loop
System.out.println(singleResult);
result +=singleResult;
result +="\n";
First, I would use a StringJoiner to gather the elements. Then, I would eliminate the many local temporary variables. Finally, I would use println in the loop and another StringJoiner for the final result. Like,
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
StringJoiner result = new StringJoiner(System.lineSeparator());
while (rs.next()) {
StringJoiner lineJoiner = new StringJoiner(", ");
if (cb1.isSelected()) {
lineJoiner.add(String.valueOf(rs.getInt("custid")));
}
if (cb2.isSelected()) {
lineJoiner.add(rs.getString("name"));
}
if (cb3.isSelected()) {
lineJoiner.add(rs.getString("address"));
}
if (cb4.isSelected()) {
lineJoiner.add(rs.getString("city"));
}
if (cb5.isSelected()) {
lineJoiner.add(rs.getString("state"));
}
if (cb6.isSelected()) {
lineJoiner.add(String.valueOf(rs.getInt("zip")));
}
System.out.println(lineJoiner);
result.add(lineJoiner.toString());
}
results.setText(result.toString());
stmt.close();
}
You could also do the same thing with Collection(s) like,
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
List<String> msg = new ArrayList<>();
while (rs.next()) {
List<String> al = new ArrayList<>();
if (cb1.isSelected()) {
al.add(String.valueOf(rs.getInt("custid")));
}
if (cb2.isSelected()) {
al.add(rs.getString("name"));
}
if (cb3.isSelected()) {
al.add(rs.getString("address"));
}
if (cb4.isSelected()) {
al.add(rs.getString("city"));
}
if (cb5.isSelected()) {
al.add(rs.getString("state"));
}
if (cb6.isSelected()) {
al.add(String.valueOf(rs.getInt("zip")));
}
String line = al.stream().collect(Collectors.joining(", "));
System.out.println(line);
msg.add(line);
}
results.setText(msg.stream().collect(Collectors.joining(System.lineSeparator())));
stmt.close();
Prefer whichever you find most readable.

jdbc Mysql nested resultset

See Below. rs.getString("tags") is subquery with more than 1 row. I want to iterate that subquery(rs.getString("tags") ---- Like rs.next().
while (rs.next()) {
emailDto emaildto = new emailDto();
emaildto.setMid(rs.getInt("id"));
emaildto.setSub(rs.getString("sub"));
emaildto.setMessage(rs.getString("message"));
while(rs.getString("tags").next()){
arrtags[i] = rs.getString(1);
}
emaildto.setTags(arrtags);
rs.getString("tags") does not work --- and contain more than 1 rows. How to extract it. Is there any technique?
Try something like this:
Array tagsArray = rs.getArray("tags");
String[] tags = (String[])tagsArray.getArray();
this is not answer. this is complete code
List emails = new ArrayList();
String listQuery = "select mid, sub, message, "
+ " (select emailid from sub_ids where sub_ids.messageid= sub_mail_list.mid ) // this query fetch more than one row.
as refid"
+ " from sub_mail_list";
PreparedStatement ps = null;
ResultSet rs;
try {
ps = DatabaseConnectionUtil.getConnection().prepareStatement(
listQuery);
rs = ps.executeQuery(listQuery);
while (rs.next()) {
emailDto emaildto = new emailDto();
emaildto.setMid(rs.getInt("mid"));
emaildto.setSub(rs.getString("sub"));
emaildto.setMessage(rs.getString("message"));
Array tagsArray = rs.getArray("refid");
List<vtbDto> vtbdtosvr = new ArrayList<vtbDto>();
int[] tags = (int[])tagsArray.getArray();
for (int i = 0; i < tags.length; i++) {
vtbDto vtbdto = new vtbDto();
vtbdto.setRefid(tags[i]);
vtbdtosvr.add(vtbdto);
}
emaildto.setAr(tagsArray);
emails.add(emaildto);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
DatabaseConnectionUtil.closeAll(ps);
}
return emails;
And this is code to print function
List emailDtos = emaildao.getAllemails();
for (emailDto emailDto2 : emailDtos) {
System.out.println( emailDto2.getMid());
System.out.println( emailDto2.getSub());
System.out.println( emailDto2.getMessage());
List<vtbDto> vtbdtos= emailDto2.getVtbdtolst();
for (vtbDto vtbdto2 : vtbdtos) {
System.out.print(vtbdto2.getRefid() + ", ");
}
}
and the console print "Subquery returns more than 1 row";

Search a JTable using multiple JTextfield

I have a JFrame that has 3 JTextfields and 2 JDatechooser, what I am trying to do is if only one JTextfield has something typed in it and I press the search button, then I will be able to retrieve the data to JTable, but the problem is I have to fill out all JTextFileds and JDatechooser in order to retrieve data. My idea is to ignore null JTextfields and JTdatechooser if only one JTextfield has the keyword I want ?? Any suggestions ?? Thanks in advance,
public ArrayList<BillsRecord> getBillRecordByID(int EmpCode, String Fname, String Lname, String sDate, String eDate) throws SQLException {
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE B.EMP_ID = ? "
+ " OR E.FNAME = ? "
+ " OR E.LNAME = ? "
+ " OR DATE BETWEEN ? AND ? "
+ " ORDER BY B.DATE";
DBConnection con = new DBConnection();
Connection connect = con.getConnection();
PreparedStatement ps = null;
ArrayList<BillsRecord> records = new ArrayList<>();
try {
ps = connect.prepareStatement(sql);
ps.setInt(1, EmpCode);
ps.setString(2, Fname);
ps.setString(3, Lname);
ps.setString(4, sDate);
ps.setString(5, eDate);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
BillsRecord billrec = new BillsRecord();
billrec.setDATE(rs.getString("DT"));
billrec.setEMP_ID(rs.getInt("EMP_ID"));
billrec.setFNAME(rs.getString("FNAME"));
billrec.setLNAME(rs.getString("LNAME"));
billrec.setMONEY_SENT(rs.getDouble("MONEY_SENT"));
billrec.setRENT(rs.getDouble("RENT"));
billrec.setPHONE(rs.getDouble("PHONE"));
billrec.setGAS(rs.getDouble("GAS"));
billrec.setELECTRICITY(rs.getDouble("ELECTRICITY"));
billrec.setINTERNET(rs.getDouble("INTERNET"));
billrec.setOTHER(rs.getDouble("OTHER"));
records.add(billrec);
return records;
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
if (ps != null) {
ps.close();
}
if (connect != null) {
connect.close();
}
}
return null;
}
private void search() {
try {
JTextField stxt = ((JTextField) startdatetxt.getDateEditor().getUiComponent());
String sDATE = stxt.getText().trim();
JTextField etxt = ((JTextField) enddatetxt.getDateEditor().getUiComponent());
String eDATE = etxt.getText().trim();
int EMP_ID = Integer.parseInt(this.empidtxt.getText().trim());
String FNAME = this.firstnametxt.getText().trim();
String LNAME = this.lastnametxt.getText().trim();
BillRecordDao billrecdao = new BillRecordDao();
ArrayList<BillsRecord> records = billrecdao.getBillRecordByID(EMP_ID, FNAME, LNAME, sDATE, eDATE);
Object[] tableColumnName = new Object[11];
tableColumnName[0] = "Date";
tableColumnName[1] = "H.License";
tableColumnName[2] = "First Name";
tableColumnName[3] = "Last Name";
tableColumnName[4] = "MONEY SENT";
tableColumnName[5] = "RENT";
tableColumnName[6] = "PHONE";
tableColumnName[7] = "GASE";
tableColumnName[8] = "ELECTRICITY";
tableColumnName[9] = "INTERNET";
tableColumnName[10] = "OTHER";
DefaultTableModel tbd = new DefaultTableModel();
tbd.setColumnIdentifiers(tableColumnName);
this.BillsSummaryTable.setModel(tbd);
Object[] RowRec = new Object[11];
for (int i = 0; i < records.size(); i++) {
RowRec[0] = records.get(i).getDATE();
RowRec[1] = records.get(i).getEMP_ID();
RowRec[2] = records.get(i).getFNAME().toUpperCase();
RowRec[3] = records.get(i).getLNAME().toUpperCase();
RowRec[4] = records.get(i).getMONEY_SENT();
RowRec[5] = records.get(i).getRENT();
RowRec[6] = records.get(i).getPHONE();
RowRec[7] = records.get(i).getGAS();
RowRec[8] = records.get(i).getELECTRICITY();
RowRec[9] = records.get(i).getINTERNET();
RowRec[10] = records.get(i).getOTHER();
tbd.addRow(RowRec);
}
} catch (SQLException e) {
System.out.println(e.toString());
}
}
Basically, you need to create a variable/dynamic query based on the available values
Now, you can do this using something like StringBuilder or even storing each query element in a List or array, but you always end up with the "trailing OR" problem (you need to know when you've got to the last element and not append the "OR" to the String or remove the trailing "OR" from the resulting String). While not difficult, it's just a pain.
However, if you're using Java 8, you can use StringJoiner!
StringJoiner sj = new StringJoiner(" OR ");
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE ";
List values = new ArrayList();
// EmpCode MUST be a Integer, so it can be null
if (EmpCode != null) {
sj.add("B.EMP_ID = ?");
values.add(EmpCode);
}
if (FName != null) {
sj.add("E.FNAME = ?");
values.add(FName);
}
if (LName != null) {
sj.add("E.LNAME = ?");
values.add(LName);
}
if (sDate != null && eDate != null) {
sj.add("DATE BETWEEN ? AND ?");
values.add(sDate);
values.add(eDate);
}
sql += sj.toString();
Connection connect = null;
try (PreparedStatement ps = connect.prepareStatement(sql)) {
for (int index = 0; index < values.size(); index++) {
ps.setObject(index + 1, values.get(index));
}
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
//...
}
}
} catch (SQLException exp) {
exp.printStackTrace();
}
You might also like to have a look at The try-with-resources Statement and have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

Executing SQL Statement by getting Boolean Java

I have 2 Frames let's name them "Request" and "Confirm". Now when clicking a Button in "Request" the Frame "Confirm" is called. And when clicking "yes" a SQL Statement should be executed. The thing is that the SQL Statement is in class "Request". The Class "Confirm" should be called from other Frames too, so I don't want to make an Action Listener on the Button "yes" in "Confirm". I what to get a boolen by clicking the "yes" Button. If its true the statement in 'Request" should be executed.
How I can do this?
ReqBnt.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
if (arg0.getSource() == ReqBnt) {
String VendN = txtVendN.getText();
String VendSN = txtVendSN.getText();
String Ad = txtAd.getText();
String Ads = txtAds.getText();
String City = txtCity.getText();
String Zip = txtZip.getText();
String UID = txtUID.getText();
String Reg = txtReg.getText();
String Rep = txtRep.getText();
String Tel = txtTel.getText();
String Fax = txtFax.getText();
String Mail = txtMail.getText();
String Iban = txtIban.getText();
String Bic = txtBic.getText();
String BInst = txtBInst.getText();
String VendInfo = txtVendInfo.getText();
String Flag = "Y";
String PT = comboPT.getSelectedItem().toString();
String Ctry = comboCtry.getSelectedItem().toString();
try{
try {
String sqlx = "SELECT `Abbreviation 2`, `Country English` From `database`.`country_master` " +
"WHERE `Country English` = '" + Ctry + "'";
PreparedStatement pstx = conn.prepareStatement(sqlx);
ResultSet rs = pstx.executeQuery();
while (rs.next()){
partCode = rs.getString("Abbreviation 2");
}}catch (Exception ex) {
System.out.println("Abbreviation Not Found");
}
String sqlFind = "Select max(substring(`Vendor Code`, 3)) From `database`.`vendor_master`";
try {
PreparedStatement pstFind = conn.prepareStatement(sqlFind);
ResultSet rs = pstFind.executeQuery();
while (rs.next()){
partNo = rs.getInt("Vendor Code")+1;
}}catch (Exception ex) {
partNo = 10001;
}
String VendC = partCode+partNo;
try {
String sqlx = "SELECT `Abbreviation Use`, `Country English` From `database`.`country_master` " +
"WHERE `Country English` = '" + Ctry + "'";
PreparedStatement pstx = conn.prepareStatement(sqlx);
ResultSet rs = pstx.executeQuery();
while (rs.next()){
CtryC = rs.getString("Abbreviation Use");
}}catch (Exception ex) {
System.out.println("Abbreviation Not Found");
}
Calendar currentDate = Calendar.getInstance(); //Get the current date
SimpleDateFormat formatter= new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
//if
// 1.step: check if there are null values
// 2.step: if there are no null values -> call frame "Confirm"
// 3.step: if Confirm = true -> execute statement
// if Confitm = fals -> do nothing
try {
String sql = "INSERT INTO `database`.`vendor_master`(`Vendor Code`,`Vendor Full Name`,`Vendor Short Name`,"+
"`Address`,`Address Suffix`,`ZIP Code`,`City`,`Country`,`Country Code`,`UID No`,`Registration No`,"+
"`Payment Term`,`Creation Date`,`IBAN`,`BIC`,`Banking Institution`,`Representive`,`Email Address`,"+
"`Telefon No`,`Fax`,`Vendor Information`,`Active Flag`) "+
"Values('"+VendC+"','"+VendN+"','"+VendSN+"','"+Ad+"','"+Ads+"','"+Zip+"','"+City+"','"+Ctry+"','"+CtryC+"','"+
UID+"','"+Reg+"','"+PT+"','"+dateNow+"','"+Iban+"','"+Bic+"','"+BInst+"','"+Rep+"','"+Mail+"','"+Tel+"','"+
Fax+"','"+VendInfo+"','"+Flag+"')";
PreparedStatement pstExecute = conn.prepareStatement(sql);
pstExecute.execute();
System.out.println("Vendor Registered");
}catch (Exception ex) {
System.out.println("Please insert required Fields!");
}
///end if
}catch (Exception ex) {
System.out.println("Error: "+ex);
}
}
}
});
Try using a JDialog instead:
int dialogResult = JOptionPane.showConfirmDialog (
null,
"Are you sure you want to do that?",
"Warning",
JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
//Do a thing here
}
You can Take a look at the dialog here:
http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
You can even extend JDialog instead if you want more functionality.

Categories