Executing SQL Statement by getting Boolean Java - 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.

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

Can i have two connection statement in a single button action performed using java swing.?

My complete code to access data from two different databases using single hive jdbc driver. I get sql exception on next database connection, before that it works perfectly. Kindly, suggest me some solution to further process. Where as next prepared statement query throws sql exception. But doing on a separate button action it works fine, while i'm doing in a single action it throws error.
String s1 = jTextField1.getText();
String s2 = jTextField2.getText();
String s3 = jTextField3.getText();
String s4 = new String(jPasswordField1.getPassword());
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/twitter_db", "arunachalam", "");
Statement st = con.createStatement();
String sql = "select dbname,tbname from check where userid='" + s3 + "'and tbname='" + s2 + "'";
String sql1 = "select userid,password from user_reg where userid='" + s3 + "'";
ResultSet rs = st.executeQuery(sql);
try {
PreparedStatement ps = con.prepareStatement(sql1);
ResultSet rs1 = ps.executeQuery();
while (rs.next() && rs1.next()) {
if ((rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
jSeparator1.setVisible(true);
jScrollPane1.setVisible(true);
try {
Connection con1 = DriverManager.getConnection("jdbc:hive2://localhost:10000/" + s1, "arunachalam", "");
ArrayList<Tweet> list = new ArrayList<Tweet>();
String ve = "select id,created_at,source,favorited,retweet_count,retweeted_status,entities,text,user,in_reply_to_screen_name from " + s2;
PreparedStatement ps1 = con1.prepareStatement(ve);
ResultSet rs2 = ps1.executeQuery();
Tweet tweet;
while (rs2.next()) {
tweet = new Tweet(rs.getLong("id"), rs.getString("created_at"), rs.getString("source"), rs.getBoolean("favorited"), rs.getInt("retweet_count"), rs.getString("retweeted_status"), rs.getString("entities"), rs.getString("text"), rs.getString("user"), rs.getString("in_reply_to_screen_name"));
list.add(tweet);
String[] columnName = {"Tweet_ID", "Created_At", "Source", "Favorited", "Retweet_Count", "Retweeted_Status", "Entities", "Text", "User", "Screen_Name"};
Object[][] twt = new Object[list.size()][10];
for (int i = 0; i < list.size(); i++) {
twt[i][0] = list.get(i).gettweetid();
twt[i][1] = list.get(i).getcreated();
twt[i][2] = list.get(i).getsource();
twt[i][3] = list.get(i).getfavor();
twt[i][4] = list.get(i).getcount();
twt[i][5] = list.get(i).getstatus();
twt[i][6] = list.get(i).getentities();
twt[i][7] = list.get(i).gettext();
twt[i][8] = list.get(i).getuser();
twt[i][9] = list.get(i).getscreen();
TheModel model = new TheModel(twt, columnName);
jTable1.setModel(model);
jTable1.setRowHeight(20);
}
}
} catch (Exception e) {
showMessageDialog(null, e);
}
break;
} else if ((!rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Database Name is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((rs.getString("dbname").equals(s1)) && (!rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Table Name is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (!rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Password is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((!rs1.getString("userid").equals(s3)) && (rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "User ID is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else {
JOptionPane.showMessageDialog(null, "Access Denied", "Error", JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception e) {
showMessageDialog(null, e);
}
} catch (Exception e) {
showMessageDialog(null, e);
}
To be responsive, as the application would freeze during actionPerformed use
invokeLater.
Yes separate connections for instance with different users, one for reading only, one for admin tasks, is quite possible. However I did not see calls to close().
(Also a single-user (such as an embedded) database might not do.)
To automatically close connection, statement and result set use try-with-resources: try (DECLARATION; ... ; DECLARATION) { ... } - saves a lot.
The explicit class loading with Class.forName no longer is needed for current drivers.
// Java 8
SwingUtilities.invokeLater(() -> {
String sql = "select dbname, tbname from check where userid=? and tbname=?";
try (Connection con = DriverManager.getConnection(
"jdbc:hive2://192.168.1.13:10000/twitter_db", "arunachalam", "");
PreparedStatement st = con.prepareStatement(sql)) {
st.setString(1, s3);
st.setString(2, s2);
try (ResultSet rs = st.executeQuery()) {
if (rs.next()) {
List<Tweet> list = new ArrayList<>();
String hive = "select id,created_at,source,favorited,retweet_count,"
+ "retweeted_status,entities,text,user,in_reply_to_screen_name from "
+ s2;
try (Connection con1 = DriverManager.getConnection(
"jdbc:hive2://localhost:10000/"+s1, "arunachalam", "");
PreparedStatement ps1 = con1.prepareStatement(hive);
ResultSet rs2 = ps1.executeQuery()) {
...
});

Form 1 is the textfield and Form 2 is the JTable how retrieve the value of Table in form 1 textfield

Form 1 is the textfield located
private void tblOrgMouseClicked(java.awt.event.MouseEvent evt) {
Connection cn = null;
Statement st = null;
ResultSet rss = null;
btnSave.setEnabled(false);
btnUpdate.setEnabled(true);
btnDelete.setEnabled(true);
try {
int row = tblOrg.getSelectedRow();
String cell_click = (tblOrg.getModel().getValueAt(row, 0).toString());
String sql = "SELECT * FROM tbl_organization WHERE org_id = '" + cell_click + "'";
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_organization?zeroDateTimeBehavior=convertToNull", "root", "");
st = cn.prepareStatement(sql);
rss = st.executeQuery(sql);
if (rss.next()) {
String addid = rss.getString("org_id");
txtOrgID.setText(addid);
String addname = rss.getString("org_name");
txtOrgName.setText(addname);
String adddesc = rss.getString("org_description");
txtOrgDesc.setText(adddesc);
String addadviser = rss.getString("org_adviser");
txtAdviserName.setText(addadviser);
}
} catch (Exception e) {
}
}
Form 2 is the Jtable
private void tblAdviserList2MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
Connection cn = null;
Statement st = null;
ResultSet rss = null;
String ab = " ";
try {
int row = tblAdviserList2.getSelectedRow();
String cell_click = (tblAdviserList2.getModel().getValueAt(row, 0).toString());
String sql = "SELECT * FROM tbl_adviser WHERE adviser_id = '" + cell_click + "'";
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_organization?zeroDateTimeBehavior=convertToNull", "root", "");
st = cn.prepareStatement(sql);
rss = st.executeQuery(sql);
if (rss.next()) {
String addid = rss.getString("firstname").concat(ab).concat(rss.getString("middlename")).concat(ab).concat(rss.getString("lastname"));
new FrmOrganization(addid);
this.setVisible(false);
}
} catch (Exception e) {
}
}
To get the value from a particular cell:
Object cellValue = table.getValueAt(row, col);
Alternatively, you can create a TableModel where each row represents a person object, and add a method on that.

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

SQL select won't show the selected item

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.

Categories