How to display data from MySQL in a JLabel? - java

How would i get the "Goal" value from my MySQL into a JLabel? Would i have to separate it into different functions?
Jlabel GOAL = new JLabel("");
try {
//connection to database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:8889/Daily", "student", "student");
Statement myStmt = myConn.createStatement();
ResultSet rs = myStmt.executeQuery("select Goal from User WHERE id=1");
GOAL.setText(rs.getString("Goal"));
}
catch (Exception e) {
e.printStackTrace();
}
GOAL.setForeground(Color.LIGHT_GREEN);
GOAL.setBounds(23, 90, 61, 45);
contentPane.add(GOAL);
`

Related

Image not visible in JLabel with mouse click in JTable

I'm making a small application for a school project. Inserting photos into SQL database is fine, I rename the photos in a JTable and can also open blob photos in SQL editor. It is not possible to make the photos visible on a JLabel.
Can someone help me on this?
The intention is to get a preview of the information that has been entered at a mouse click. the application is an image bank where you can enter different healthcare devices.
Code JTable
DefaultTableModel model = (DefaultTableModel) tableDom.getModel();
try {
Class.forName("com.mysql.jdbc.Driver"); //database connectie maken
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybrains?
allowMultiQueries=true&serverTimezone=America/Winnipeg&dummyparam=", "", "")) {
String sql = "Select * from Telefonie ";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery(sql);
model.setRowCount(0);
while (rs.next()) {
int id = rs.getInt("ID");
String naam = rs.getString("naam"); // naam is een kollom in de database
String model_type = rs.getString("Model_Type");
String functionaliteit = rs.getString("Functionaliteit");
String troubleshoot = rs.getString("Troubleshoot");
String oplossing = rs.getString("Oplossing");
String voorbeeld = rs.getString("Fotonaam");
byte[] fotos = rs.getBytes("Uploadfoto");
// ImageIcon imageicon = new ImageIcon(fotos);
//voorbeeldfoto.setIcon(imageicon);
//voorbeeldfoto.setIcon(foto());
model.addRow(new Object[]{id, naam, model_type, functionaliteit, troubleshoot,
oplossing, voorbeeld, fotos});
}
}
} catch (ClassNotFoundException | SQLException e) {
}
Code Mouse Clicked
try {
int i = tableDom.getSelectedRow();
Class.forName("com.mysql.jdbc.Driver"); //database connectie maken
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybrains?
allowMultiQueries=true&serverTimezone=America/Winnipeg&dummyparam=", "", "");
String sql = "Select * from Telefonie";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery(sql);
if (rs.next());
//int i = tableDom.getSelectedRow();
TableModel model = tableDom.getModel();
iD.setText(model.getValueAt(i, 0).toString());
name.setText(model.getValueAt(i, 1).toString());
modelt.setText(model.getValueAt(i, 2).toString());
func.setText(model.getValueAt(i, 3).toString());
oplos.setText(model.getValueAt(i, 4).toString());
troubl.setText(model.getValueAt(i, 5).toString());
photoNaam.setText(model.getValueAt(i, 6).toString());
byte[] voorbeeldfoto = rs.getBytes("Uploadfoto");
JLabel image1 = (JLabel) model.getValueAt(i, 8);
ImageIcon image1Icon = (ImageIcon) image1.getIcon();
voorbeeldfoto.setIcon(image1Icon);
} catch (ClassNotFoundException | SQLException ex) {
JOptionPane.showMessageDialog(rootPane, name);
}
}

Insert Date from java (eclipse) to Sql (workbench)

I entered the code and I wanted to send this data to the prepared table in Workbench (SQL). The system shows no connection. I work in an eclipse environment and I have problems to send data from jtable to Workbench
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/tabela2?autoReconnect=true&useSSL=false","root","Jackpatu205");
String insert = "insert into autohandel values (?, ? , ? , ?,?)";
PreparedStatement ps = (PreparedStatement) conn.prepareStatement(insert);
ps.setString(1, "1");
ps.setString(2, "Citroen");
ps.setString(3, "2015");
ps.setString(4, "12500");
ps.setString(5,"France");
ps.executeUpdate();
if (conn !=null) {
System.out.println("\nConnected Update");
System.out.println(" --------------------------------------");
}
}catch (Exception e) {
System.out.print("No Connection Update");
}
//
}
});

Deleting data in table (SQLite) through java (Eclipse)

as the title suggests, ive been trying to delete data in a table in my SQLite through the use of a button. I have been able to make it work on another class, but i cant seem to make it work on this specific class which i will show you.
the button is called btnDelete, and the method that loads the database and deletes it is called delete_account.
Button btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
Here's the whole code in the class just in case it is needed:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class AccSettings {
private JFrame frmAccountSett;
private JTextField txtFullname;
private JTextField txtUsername;
private JPasswordField txtPassword;
private int userid;
private String user;
/**
* Create the application.
*/
public AccSettings(String username) {
user=username;
//userid = id;
initialize();
edit_account();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmAccountSett = new JFrame();
frmAccountSett.setTitle("Account Settings");
frmAccountSett.setBounds(100, 100, 450, 300);
frmAccountSett.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAccountSett.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Edit Username:");
lblUsername.setBounds(85, 62, 103, 14);
frmAccountSett.getContentPane().add(lblUsername);
txtUsername = new JTextField();
txtUsername.setBounds(229, 59, 137, 20);
frmAccountSett.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(229, 90, 137, 20);
frmAccountSett.getContentPane().add(txtPassword);
JButton btnConfirm = new JButton("Confirm Changes");
btnConfirm.setBounds(146, 164, 137, 29);
frmAccountSett.getContentPane().add(btnConfirm);
JLabel lblPassword = new JLabel("Edit Password:");
lblPassword.setBounds(85, 93, 103, 14);
frmAccountSett.getContentPane().add(lblPassword);
frmAccountSett.setVisible(true);
JButton btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
btnDelete.setBounds(299, 227, 125, 23);
frmAccountSett.getContentPane().add(btnDelete);
JButton btnBack = new JButton("<< Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frmAccountSett.dispose();
}
});
btnBack.setBounds(10, 227, 103, 23);
frmAccountSett.getContentPane().add(btnBack);
JLabel lblFullname = new JLabel("Edit Fullname:");
lblFullname.setBounds(85, 31, 103, 14);
frmAccountSett.getContentPane().add(lblFullname);
txtFullname = new JTextField();
txtFullname.setColumns(10);
txtFullname.setBounds(229, 28, 137, 20);
frmAccountSett.getContentPane().add(txtFullname);
btnConfirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
update_account();
}
});
}
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
public void update_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
#SuppressWarnings("deprecation")
String query="UPDATE tblUsers SET fullname='" + txtFullname.getText()+"',"
+ "username='" + txtUsername.getText()+"',"
+ "password='" + txtPassword.getText()+"'"
+ "WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Reference successfully updated!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
//load the results
public void edit_account()
{
try {
Connection con; //create a variable for con
Database db = new Database(); //create an instance of database class
con = db.open_connection(); //set con as connection form database class
Statement st;
st = con.createStatement();
//create a statement variable
//create the query that will search the table based on similar terms
String query = "SELECT * FROM tblUsers WHERE userID=" + userid+ "";
//get the resultset of the query (rows)
ResultSet rs = st.executeQuery(query);
if (rs.next())
{
do{
txtFullname.setText(rs.getString(2));
txtUsername.setText(rs.getString(3));
txtPassword.setText(rs.getString(4));
}
while(rs.next());
}
/*
else {
JOptionPane.showMessageDialog(null, "Edit failed");
}
*/
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I believe the problem stems mostly from userID which zephyr has stated. I followed a code from another class(frmEditRef), but that class uses a JScrollPane, which when called from another class (frmMainInterface) looks like this:
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
int x = table.getSelectedRow(); //get the current row
int ans = JOptionPane.showConfirmDialog(null, "Do you want to edit this record?");
if (ans == 0) {
//proceed to edit the transaction
//get the id
String id = String.valueOf(model.getValueAt(x, 0));
new EditRef(user,Integer.valueOf(id));
frmUserRef.dispose();
}
}
});
The class im trying to work with does not use JScrollPane. Therefore the coding to it would be different. Here's how it looks like from frmMainInterface:
btnAccountSett.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String id = ;
new AccSettings(user,Integer.valueOf(id));
}
});
As you can see, i have no idea what to put in after the "String id =".
I hope this explanation can get through you guys. I myself am having difficulty trying to explain something i dont even fully understand.

retrive and display multiple BLOB images from mySQL DB

I have managed to display the first image but it does not display the next blob image in the column
PS. i have double checked everything in the DB even used the query in a Workbench THE query in the code is correct!, it returns exactly what i wanted
Thank you in advance.
My code:
public BufferedImage image()
{
System.out.println("I am in Image");
try {
System.out.println("trying to find com.mysql.jdbc.driver");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
System.out.println("Success");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select image from images where state = 0 ");
while (rs.next())
{
java.sql.Blob blob = rs.getBlob(1);
System.out.println(blob);
System.out.println(blob.length());
InputStream in = blob.getBinaryStream(1,blob.length());
System.out.println(!rs.next());
System.out.println(in);
BufferedImage image = ImageIO.read(in);
System.out.println(image);
// Display the image
ImageIcon icon = new ImageIcon(image);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(500,800);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
return image;
}
con.close();
System.out.println("reached here");
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
the Problem was that for some reason it was skipping one row after changing if(!rs.next) to
if (rs.next())
{
anyResults = true;
Blob blob = rs.getBlob("image");
id = rs.getInt("id");
System.out.println(id);
System.out.println(blob);
System.out.println(blob.length());
InputStream in = blob.getBinaryStream(1, blob.length());
now it works for me

JDBC JTable image

I have an item database (jdbc) the functionality is: insert, delete, and update using GUI JTable, all work good but I need to display the image in the JTable but I couldn't :(
If you could help me in that, here's the code for the main functionality:
fill Table method:
try{
connection= DriverManager.getConnection(url, usr, pas);
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from item");
itemTable.setModel(DbUtils.resultSetToTableModel(resultSet));
} catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex);}
add method:
try{
PreparedStatement insert =connection.prepareStatement("INSERT INTO items"
+"(name, price, image, ID)"
+"VALUES(?,?,?,?)");
insert.setString(1, nameTextField.getText());
insert.setDouble(2, Double.parseDouble(priceTextField.getText()));
insert.setByte(3, image);
insert.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = insert.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
update method:
try{
PreparedStatement update =connection.prepareStatement("update item set "
+ "name=? , price=?, image=? where id=?""
+"VALUES(?,?,?,?)");
update.setString(1, nameTextField.getText());
update.setDouble(2, Double.parseDouble(priceTextField.getText()));
update.setByte(3, image);
update.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = update.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
delete method:
try{
Statement delete = connection.createStatement();
delete.executeUpdate("delete from item where id="+IDTextField.getText());
priceTextField.setText("");
nameTextField.setText("");
idTextField.setText("");
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
A button event to choose image from JFileChooser:
String imagePath = null;
JFileChooser file;
private void ChooseImageButtonActionPerformed(java.awt.event.ActionEvent evt){
int result = file.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
imagePath = path;
}
}
The important methods are fillTable() and add().
fillTable method could be like this:
//you need a TableModel, let´s call it model and let´s call your JTable myJTable
TableModel model = (javax.swing.table.DefaultTableModel) myJTable.getModel();
myJTable.setModel(model);
//try to add results
try {
connection = DriverManager.getConnection(url, usr, pas);
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from item");
while (resultSet.next()) {
//after your query, get the Image
Blob blob = resultSet.getBlob(3);//column 3
byte[] data = blob.getBytes(1, (int) blob.length());
BufferedImage img = null;
img = ImageIO.read(new ByteArrayInputStream(data));
Icon imgToTable = imageToIcon(img);//use the method below
//add row to your table (throught the model)
model.addRow(new Object[]{resultSet.getObject(1).toString(), resultSet.getObject(2).toString(), imgToTable,resultSet.getObject(4).toString()});
//itemTable.setModel(DbUtils.resultSetToTableModel(resultSet));
}
resultSet.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
Add method could be like this:
try{
PreparedStatement insert =connection.prepareStatement("INSERT INTO items"
+"(name, price, image, ID)"
+"VALUES(?,?,?,?)");
insert.setString(1, nameTextField.getText());
insert.setDouble(2, Double.parseDouble(priceTextField.getText()));
//i recommend to use something like this to configure you image
file = new File(imagePath);
fis = new FileInputStream(file);
if (null == fis) {
fis = new FileInputStream(imagePath);
}
//configure image
insert.setBinaryStream(3, fis);
// insert.setByte(3, image);
insert.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = insert.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
And use this to convert from Image to Icon (to put it in a Table Cell):
//from Image a Icon
public Icon imageToIcon(Image image) {
ImageIcon imgIcon = new ImageIcon(image);
Icon iconReturn = (Icon) imgIcon;
return iconReturn;
}
If in your database you are not using blob let me know.

Categories