swing retrieve data from mysql db to textfield - java

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();

Related

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) {
}
}
}

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

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.

Unable to insert data in mysql database using JDBC in Netbeans

I used it inside the button action made database, even connected the database but the information is not going inside the table of the data base.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhoast:3306//a","root","root");
Statement smt = conn.createStatement();
ps = conn.prepareStatement("insert into aone values (?,?,?)");
String n = name.getText();
String a = age.getText();
String r = roll.getText();
ps.setString(1,n);
ps.setString(2,a);
ps.setString(3,r);
int i = ps.executeUpdate();
if (i>0) {
JOptionPane.showMessageDialog(null, "data is saved");
}
else {
JOptionPane.showMessageDialog(null, "error");
}
}
catch(Exception e) {
}
}
Print the stack trace in the catch block. The JVM might be throwing an exception, but you'll never know it this way.
When you do that, I'm sure you'll be told that JDBC could not connect to "localhoast".
I doubt that "localhoast" is correct; try "localhost".
There are so many things wrong with this code:
Should not mingle UI and database code.
Should not get JDBC connection with every request; use a pool.
Code is not layered; hard to test.
You don't close any JDBC resources in method scope.
Try it like this:
private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/a","root","root");
ps = conn.prepareStatement("insert into aone values (?,?,?)");
String n = name.getText();
String a = age.getText();
String r = roll.getText();
ps.setString(1,n);
ps.setString(2,a);
ps.setString(3,r);
int i = ps.executeUpdate();
if (i > 0) {
JOptionPane.showMessageDialog(null, "data is saved");
} else {
JOptionPane.showMessageDialog(null, "error");
}
} catch(Exception e) {
e.printStackTrace();
} finally {
close(ps); // You need to implement this
close(conn); // You need to implement this
}
}

Save edited cell/s from JTable to database

Newbie to JTable. Just got in today.
So I am able to populate my data from database into a JTable.
I am currently stuck in saving the edited cell/s into the database.
I've read many articles. But I haven't found the one
Just a button then save!
Here's my code
public class DBEngine {
Connection con = IQConnection.getConnectionMgrInstance().getConnection();
PreparedStatement pstm = null;
ResultSet rs = null;
public Vector getEmployee() throws Exception{
Vector<Vector<String>> employeeVector = new Vector<Vector<String>>();
try {
if (con != null) {
String query = "SELECT * FROM OGG.TBLSAMPLE";
try {
pstm = con.prepareStatement(query);
rs = pstm.executeQuery();
while(rs.next()) {
Vector<String> employee = new Vector<String>();
employee.add(rs.getString(1)); //Empid
employee.add(rs.getString(2)); //name
employee.add(rs.getString(3)); //position
employee.add(rs.getString(4)); //department
employeeVector.add(employee);
}
} catch (Exception e) {
e.printStackTrace();
}
}else{
//lbl_err1.setText("Error");
}
} catch (Exception e) {
e.printStackTrace();
//flag = false;
//lbl_err1.setText("Failed!");
} finally {
try{
if(rs != null){
rs.close();
}
}catch(Exception e){
}
try{
if(pstm != null){
pstm.close();
}
}catch(Exception e){
}
}
return employeeVector;
}
}
Thanks!
use preparedstatement like this way for inserting into DB
PreparedStatement pt=con.prepareStatement("insert into mytable values(?) ");
pt.setString(1,ID);
int result=pt.executeUpdate();
if you want to update then use this way
PreparedStatement pt=con.prepareStatement("update mytable set column_name=? ");
pt.setString(1,ID);
int result=pt.executeUpdate();

I need to restart glassfish after using for some time my website

When i run my website it on glassfish server everything works fine but after some time its stop responding and I need to restart glassfish.. I think its cause I not closing the connection. Can someone tell me if this is the problem? if yes how to close it? Here is one of my function.
public Album get_album (String title)
{
try{
//creates a connection to the server
Connection cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
PreparedStatement pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
ResultSet rs = pst.executeQuery();
if(rs.next()) {
Album a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
return a;
}
}
catch (Exception e) {
String msg = e.getMessage();
}
return null;
}
Assumming the unique error in your application is for not closing the resources after using them, your code should change to:
public Album get_album (String title) {
Connection cn = null;
PreparedStatement pst = null;
ResultSet rs = null;
Album a = null;
try{
//creates a connection to the server
cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
rs = pst.executeQuery();
if (rs.next()) {
a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
//don't return inside try/catch
//return a;
}
} catch (Exception e) {
String msg = e.getMessage();
//handle your exceptions
//e.g. show them in a logger at least
e.printStacktrace(); //this is not the best way
//this will do it if you have configured a logger for your app
//logger.error("Error when retrieving album.", e);
} finally {
closeResultSet(rs);
closeStatement(pst);
closeConnection(cn);
}
return a;
}
public void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeStatement(Statement st) {
if (st!= null) {
try {
st.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeResultSet(ResultSet rs) {
if (rs!= null) {
try {
rs.close();
} catch (SQLException e) {
//handle the exception...
}
}
}

Categories