Java, Mysql: how to connect dependent combobox based on another one - java

I'm seeking how to execute ActionPerformed on the first combobox in order to filter the next one. This is based on Mysql.
I'm using the following codes to fill the first combo, which is working fine
Vector<String> comboBoxItems = new Vector<String>();
final DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>(comboBoxItems);
try {
new MconnectionDB();
} catch (SQLException e2) {
e2.printStackTrace();
}
PreparedStatement st1 = null;
ResultSet rs1=null;
String strPro = "";
String sql1 ="select distinct T_AdressePro from t_adresse order by T_AdressePro";
try {
st1= MconnectionDB.con.prepareStatement(sql1);
rs1 = st1.executeQuery();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
while (rs1.next()){
strPro =rs1.getString("T_AdressePro");
comboBoxItems.add(strPro);
comboBoxPro= new JComboBox<String>(model);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
rs1.close();
st1.close();
new MdeconnectionDB();
}
catch (SQLException e) {
e.printStackTrace();
}
}
And then, I'm adding another similar code in ActionPerformed on the first combo to filter the second one:
comboBoxPro.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Vector<String> comboBoxItemsC = new Vector<String>();
final DefaultComboBoxModel<String> modelC = new DefaultComboBoxModel<String>(comboBoxItemsC);
String strCir = "";
PreparedStatement st2 = null;
ResultSet rs2=null;
String sql2 ="select distinct T_AdresseCir from t_adresse where T_AdressePro=? order by T_AdresseCir";
try {
new MconnectionDB();
} catch (SQLException e2) {
e2.printStackTrace();
}
comboBoxPro.getSelectedItem();
strProCombo = comboBoxPro.getSelectedItem().toString();
System.out.println(strProCombo);
try {
st2= MconnectionDB.con.prepareStatement(sql2);
st2.setString(1, strProCombo); //strProCombo
rs2 = st2.executeQuery();
}catch (SQLException e1) {
e1.printStackTrace();
}
try {
while (rs2.next()){
System.out.println(rs2.getString("T_AdresseCir"));
strCir =rs2.getString("T_AdresseCir");
comboBoxItemsC.add(strCir);
comboBoxCir= new JComboBox<String>(modelC);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
rs2.close();
st2.close();
new MdeconnectionDB();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
});
I'm noticing that the follogwing code "System.out.println(rs2.getString("T_AdresseCir"));" is returning the expected result but not the combobox. Still empty. Your support please, thanks.

In your actionPerformed method you are creating new JComboBox but you don't add it to gui. That is probably why you can't see its contents. You should instead create new ComboBoxModel and set it on existing JComboBox. You should probably use try with resources too to make your code more readable.
Pseudo code (I don't have your database):
// create new model for your comboBox
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
// fill model with data
try (Connection con = /*get connection to your db by any means necessary*/;
PreparedStatement stmt = con.prepareStatement(/*your query*/);
ResultSet rs = stmt.executeQuery();) {
while (rs.next()) {
model.addElement(rs.getString(/*your column*/));
}
comboBox.setModel(model); // set model for your JComboBox
} /*catch and all that*/
// no need for finally because try-with-resources.

Related

Compare csv file with MySQL database

I am creating a program in Java and I need to compare if data in a csv file is exactly the same that exists on a mysql table?
How can i do that?
For example, i have a table "Suplyers" with columns "Id, Name and Adress".
Thanks
Below is the code that i have that read csv file and that connect to database and shows the data in the table.
public static void le_csv() {
String row;
BufferedReader csvReader = null;
try {
csvReader = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\ficheiros\\fornecedores.csv"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while ((row = csvReader.readLine()) != null) {
String[] data = row.split(",");
System.out.println(data[0] + "\t" + data[1] + "\t" + data[2]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
csvReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
>
>
>
public static void query(){
try {
String url = "jdbc:mysql://127.0.0.1:3306/database";
String user = "user";
String password = "password";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
String sql = "SELECT * FROM SUPLYERS";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3);
}
rs.close();
st.close();
conn.close();
} catch (Exception exc) {
exc.printStackTrace();
}
}
You may collect the CSV data and DB data into lists of String and then compare the lists using equals:
public static List<String> readCsvData() {
List<String> csvData = new ArrayList<>();
// use try-with-resources to auto close reader
try (BufferedReader csvReader = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\ficheiros\\fornecedores.csv"))){
String row;
while ((row = csvReader.readLine()) != null) {
String[] data = row.split(",");
row = String.join("\t", data[0], data[1], data[2]);
System.out.println(row);
csvData.add(row);
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return csvData;
}
public static void initDb() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static List<String> readDbData(){
initDb();
String url = "jdbc:mysql://127.0.0.1:3306/database";
String user = "user";
String password = "password";
String sql = "SELECT * FROM SUPLYERS";
List<String> dbData = new ArrayList<>();
// use try-with-resources to auto close SQL connection, etc.
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
) {
while (rs.next()) {
String row = String.join("\t", rs.getString(1), rs.getString(2), rs.getString(3));
System.out.println(row);
dbData.add(row);
}
} catch (Exception exc) {
exc.printStackTrace();
throw new RuntimeException(exc);
}
return dbData;
}
public static boolean areCsvDataSameAsDb() {
List<String> csvData = readCsvData();
List<String> dbData = readDbData();
return csvData.equals(dbData);
}
Or you can read the data row by row to shortcut the check as soon as any discrepancy is detected.

Keep particular data in a JTable from database

I want to show particular data that keep one by one data in jtable, but never show all data,
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
String txt = jTextField1.getText().toString();
Connection cn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
cn = Dataconnection.getConnection();
qr = "SELECT p.ProductCode,p.ProductName, p.ProductPrice FROM
customer.product p WHERE CONCAT(p.ProductCode, p.ProductName) LIKE '%"+txt+"%'";
ps=cn.prepareStatement(qr);
ps.setString(1, jTextField1.getText());
rs=ps.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
rs.close();
ps.close();
} catch (Exception e) {
}
}
}

JDBC connection leak

I am currently facing connection leak problem in my code (Java , Struts). I have closed all the result sets, prepared statements, callable statements and the connection in the finally blocks of all the methods in my dao. still I face the issue.Additional information is , I am using StructDescriptor.createDescriptor for creating oracle objects. Will it cause any connection leaks? Please advise.
Code below
public boolean updatedDetails(Distribution distribution, String appCode, Connection dbConnection) {
boolean savedFlag = true;
CallableStatement updateStoredProc = null;
PreparedStatement pstmt1 = null;
try {
logger.debug("In DistributionDAO.updatedDistributionDetails");
//PreparedStatement pstmt1 = null;
ARRAY liArray = null;
ARRAY conArray = null;
ARRAY payArray = null;
ArrayDescriptor licenseeArrDesc = ArrayDescriptor.createDescriptor(LICENSEE_TAB, dbConnection);
ArrayDescriptor contractArrDesc = ArrayDescriptor.createDescriptor(DISTRIBUTION_CONTRACT_TAB, dbConnection);
ArrayDescriptor paymentArrDesc = ArrayDescriptor.createDescriptor(DISTRIBUTION_PAYMENT_TAB, dbConnection);
licenseeArray = new ARRAY(licenseeArrDesc, dbConnection, licenseeEleList.toArray());
contractArray = new ARRAY(contractArrDesc, dbConnection, contractEleList.toArray());
paymentArray = new ARRAY(paymentArrDesc, dbConnection, paymentEleList.toArray());
updateStoredProc = dbConnection.prepareCall("{CALL DIS_UPDATE_PROC(?,?,to_clob(?),?,?,?,?)}");
updateStoredProc.setLong(1, distribution.getDistributionId());
updateStoredProc.setString(2, distribution.getId());
updateStoredProc.setString(3, distribution.getNotes());
updateStoredProc.setString(4, distribution.getNotesUpdateFlag());
updateStoredProc.setArray(5, liArray);
updateStoredProc.setArray(6, conArray);
updateStoredProc.setArray(7, payArray);
String sql1="Update STORY set LAST_UPDATE_DATE_TIME= sysdate WHERE STORY_ID = ? ";
pstmt1=dbConnection.prepareStatement(sql1);
pstmt1.setLong(1,distribution.getStoryId());
pstmt1.execute();
List<Object> removedEleList = new ArrayList<Object>();
removedEleList.add(createDeleteElementObject(removedEle, dbConnection));
catch (SQLException sqle) {
savedFlag = false;
} catch (Exception e) {
savedFlag = false;
} finally {
try {
updateStoredProc.close();
updateStoredProc = null;
pstmt1.close();
pstmt1 = null;
dbConnection.close();
} catch (SQLException e) {
}
}
return savedFlag;
}
// Method createDeleteElementObject
private Object createDeleteElementObject(String removedEle,
Connection connection) {
StructDescriptor structDesc;
STRUCT structObj = null;
try {
structDesc = StructDescriptor.createDescriptor(DISTRIBUTION_REMOVED_ELEMENT_OBJ, connection);
if(removedEle != null) {
String[] tmpArr = removedEle.split("\\|");
if(tmpArr.length == 2) {
Object[] obj = new Object[2];
String eleType = tmpArr[0];
long eleId = Integer.parseInt(tmpArr[1]);
obj[0] = eleType.toUpperCase();
obj[1] = eleId;
structObj = new STRUCT(structDesc, connection, obj);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
} catch (NumberFormatException e) {
} catch (SQLException e) {
}
return structObj;
}
Some hints on your code:
You pass a Connection variable into your call but close it inside your call - is the caller aware of that fact? It would be cleaner to get the connection inside your code or return it unclosed (calling method is responsible)
Exceptions are meant to be caught, not ignored - you don't log your exception - you'll never know what happens. I bet a simple e.printStackTrace() in your catch blocks will reveal helpful information.
Use try-with-resource (see this post)
//Resources declared in try-with-resource will be closed automatically.
try(Connection con = getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
//Process Statement...
} catch(SQLException e) {
e.printStackTrace();
}
At the very least put every close inside single try-catch:
} finally {
try {
if(updateStoredProc != null) {
updateStoredProc.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(pstmt1!= null) {
pstmt1.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(dbConnection != null) {
dbConnection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

swing retrieve data from mysql db to textfield

i have column in mysql table have 100 record ,i want show values from table inside textfield ( every 3 second show record from 0 - 99). this is my code :
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String dbUrl = "jdbc:mysql://localhost:3306/jointdb";
String dbUsr = "root";
String dbPass = "a12345";
try{
String sql= "select expert1 from eridb";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection (dbUrl,dbUsr,dbPass);
st = conn.createStatement();
rs = st.executeQuery(sql);
// textField1.setText("enter text here");
while(rs.next()){
//Get values
String value = rs.getString("expert1");
textField1.setText(value);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
Now, i want show value of record every 3 second from index 0-99 record
Note: Data come to database every 3 second
thanks
Use Thread.sleep(milliseconds)
while(rs.next()){
String value = rs.getString("expert1");
textField1.setText(value);
try {
Thread.sleep(3000);
} catch(Exception e) {}
}
You can use Thread for parallel process.
Please read How To Use Swing Timer and The Event Dispatch Thread.
Use then javax.swing.Timer to re-read the data from database and set the content on the JTextField the way you need it.
Timer timer = new Timer(3000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
.... // retrieve data and prepare the textField content
textField.setContent(...);
}
});
timer.start();

JComboBox as search field

I refer this first and edited like this..same combobox name.but when I call this method it ask for a keyEvent..for that what should I do.and is there any wrong with this code
ResultSet rset;
public void srKeyTyped(java.awt.event.KeyEvent evt){
String sch = ((JTextField)ComboItemName.getEditor().getEditorComponent()).getText();
try {
rset = new JDBC.DB().getData("SELECT * FROM item_reg WHERE id = '"+sch+"'");
} catch (Exception e) {
System.out.println(e);
}
ComboItemName.removeAllItems();
try {
while (rset.next()) {
String item = rset.getString("id");
ComboItemName.addItem(item);
}
} catch (SQLException ex) {
System.out.println(ex);
//Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sch);
ComboItemName.setSelectedItem(null);
ComboItemName.setPopupVisible(true);
((JTextField)ComboItemName.getEditor().getEditorComponent()).setText(sch);
}

Categories