I'm trying to display a list of data when I click on a button.
Now, I have a an homepage (a jframe that is the homepage of the program) with a button that will open the list frame and that button, when it will be clicked, will get the data from my DB and update the table.
This is the code that I've wrote on the button that is in the homepage and not in the list frame
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new List().setVisible(true);
}
});
this.dispose();
String DB_URL = "jdbc:mysql://localhost:3306/registropassword?autoReconnect=true&useSSL=false";
String DB_Username = "root";
String DB_Password = "root";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, DB_Username, DB_Password);
PreparedStatement prepstmt = null;
ResultSet rs = null;
String query = "SELECT * FROM registro";
prepstmt = conn.prepareStatement(query);
rs = prepstmt.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch (ClassNotFoundException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
NOTE:
On this line of code the jTable2, that is the name of the table that should be updated, I got a 'cannot find symbol' error on this line.
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
Can someone help me to figure out where I'm wrong?
Related
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);
}
}
I created a login GUI login form and tried to login if the username and password matches with that entered in the database. But, I am unable to login
I could not find any error in the code.
public class Login {
private JTextField nameTextField;
private JButton submitButton;
private JTextField passwordTextField;
private JLabel Message;
private JPanel LoginPanel;
public static void main(String[] args) {
JFrame frame=new JFrame("Login");
frame.setContentPane(new Login().LoginPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(650,500);
frame.setVisible(true);
}
public Login() {
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_db", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from employee");
while (rs.next()) {
if (rs.getString("name").equals(nameTextField.getText()) && rs.getString("password").equals(passwordTextField.getText())) {
Message.setText("Login Success");
}
else {
Message.setText("Failed");
}
}
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
});
}}
If the password and username matches, I want the application to show the message "Login Success"
Currently you're scanning the whole table and in fact check the username/password of the last element in the DB.
I would simply get the (unique) element corresponding to the username entered and verify the password.
Something like this:
PreparedStatement st = con.prepareStatement("SELECT password FROM employee WHERE name = ?");
st.setString(1, nameTextField.getText().trim());
ResultSet rs = st.executeQuery();
if (rs.next() && rs.getString(1).equals(passwordTextField.getText()))
Message.setText("Login Success");
else
Message.setText("Failed");
rs.close();
con.close();
I have Java jdk1.7xxx installed and a MySQL database v5.7 too.
My database is named "mydb".
I access it from the mysql console.
However when I try to access it from my java program it makes an error "source of data unknown, or pilot name not specified". So I am missing some pilot/extra file I guess. But I did import java.sql.* at the beginning of my program..
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.*;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import java.sql.*;
import java.util.*;
public class DPIA_impacts extends JFrame {
// Labels
JLabel lb_title;
JTable tableau = null;
static JPanel p_global, p_title, p_center, p_south;
JScrollPane scroll=null;
JButton btn_Save, btn_Export;
//DefaultTableModel model;
ArrayList t1=new ArrayList();
ArrayList t2=new ArrayList();
ArrayList t3=new ArrayList();
public DPIA_impacts(){
//declarations
p_global = new JPanel();
p_title = new JPanel();
p_center = new JPanel();
p_south = new JPanel();
lb_title = new JLabel("DPIA meeting: fill the table !");
btn_Save = new JButton("Save");
btn_Export = new JButton("Export");
scroll = new JScrollPane();
// add tool tip text to the Save and Export buttons
btn_Save.setToolTipText("Save to the database Impacts table");
btn_Export.setToolTipText("Exports the contents of the Jtable to an Excel file");
// add Action Listener to the buttons
btn_Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("You clicked the button SAVE");
String url = "jdbc:mysql://localhost/mydb";
String login = "root";
String passwd = "toor";
Connection cn = null;
Statement st = null;
try {
//chargement du driver
Class.forName("com.mysql.jdbc.Driver");
// Recup connexion
cn = DriverManager.getConnection(url, login, passwd);
// Creation d'un statement
st = cn.createStatement();
String sql = "SELECT * FROM impacts";
st.executeUpdate(sql);
//instruction.executeQuery(req);
} // Try
catch (SQLException ex)
{
System.out.println("Connexion à la base de données impossible");
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
System.out.println("Pilote de connexion introuvable");
ex.printStackTrace();
//}//end catch
} finally {
try{
cn.close();
st.close();
} catch (SQLException sqle){
sqle.printStackTrace();
}
}
}});
btn_Export.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("You clicked the button EXPORT");
}
});
//add the components to the righ panels
p_title.add(lb_title);
p_center.add(scroll);
p_south.add(btn_Save, BorderLayout.WEST);
p_south.add(btn_Export, BorderLayout.EAST);
String req = "SELECT * FROM impacts";
int i =0;
Connect resultat = new Connect(req,1,"BaseDeDonnees");
// connexion a la base de donnees
}//end constructor
public static void main(String args[]) {
//Create and set up the window.
DPIA_impacts f = new DPIA_impacts();
f.setTitle("DPIA: check the impacts");
//f = new JFrame("DPIA: Impacts");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(p_title, BorderLayout.PAGE_START);
f.getContentPane().add(p_center, BorderLayout.CENTER);
f.getContentPane().add(p_south, BorderLayout.PAGE_END);
f.pack();
f.setSize(500, 300);
f.setVisible(true);
}//end main
}//end programm !
Adding the jar:
I think that in String url = "jdbc:mysql://localhost/mydb";
you forgot to write the port number.
try String url ="jdbc:mysql://127.0.0.1:3306/mydb";
UPDATE
Ok, just try this code and run it from Eclipse and not from cmd.
Also you use executeUpdate for INSERT. For SELECT you use executeQuery.
//Execute when button is pressed
System.out.println("You clicked the button SAVE");
String url = "jdbc:mysql://127.0.0.1:3306/mydb";
String login = "root";
String passwd = "toor";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
System.out.println("Connecting to database..");
try {
cn = DriverManager.getConnection(url, login, passwd);
System.out.println("Database Connected");
st = cn.createStatement();
String sql = "SELECT * FROM impacts";
rs = st.executeQuery(sql);
while (rs.next()){
//do something
}
//instruction.executeQuery(req);
} // Try
catch (SQLException ex)
{
System.out.println("Connexion à la base de données impossible");
ex.printStackTrace();
}
finally {
try{
if (cn != null ){
cn.close();
}
if (st != null ){
st.close();
}
if (rs != null ){
rs.close();
}
} catch (SQLException sqle){
sqle.printStackTrace();
}
}
I have two MySQL tables as image below
movie
movie_title
JComboBox combo = new JComboBox();
combo.setBounds(125, 15, 190, 20);
try {
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select title FROM movie_title";
PreparedStatement ps=connect.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("title");
combo.addItem(name);
}
} catch (Exception e) {
System.out.println("null");
}
combo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
JComboBox comboBox=(JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
displayDay(selected);
}
private void displayDay(Object selected) {
// TODO Auto-generated method stub
try {
combo1.removeAllItems();
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select movie_day FROM movie WHERE movie_title = ?";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setObject(1, selected);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String day = rs.getString("movie_day");
combo1.addItem(day);
}
} catch (Exception e) {
System.out.println("null");
}
}
});
I have implemented ActionListener in comboBox. When user select movie Marvel's Captain America, it will get the movie_day item from movie and load into combo1. Is there a way I can make the combo1 display the movie_day which is Sunday, 28 Apr 2016 one time only instead of two ?
Edit
private void displayDay(Object selected) {
// TODO Auto-generated method stub
try {
combo1.removeAllItems();
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select movie_day FROM movie WHERE movie_title = ?";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setObject(1, selected);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String day = rs.getString("movie_day");
DefaultComboBoxModel model = (DefaultComboBoxModel)combo1.getModel();
if (model.getIndexOf(day) == -1)
{
combo1.addItem(day);
}
}
} catch (Exception e) {
System.out.println("null");
}
Is there a way I can make the combo1 display the movie_day which is Sunday, 28 Apr 2016 one time only instead of two ?
Before adding the date to the combo box you need to check if the date already exists.
DefaultComboBoxModel model = (DefaultComboBoxModel)comboBox.getModel();
if (model.getIndexOf(theDate) == -1)
{
comboBox.addItem( theDate );
}
You could also change the SQL statement to only get "unique" dates, but I don't know SQL well enough to give you the actual syntax. Maybe this SQL Tutorial will help, otherwise you need to find a better tutorial.
Everytime I delete something from my JButton it deletes in the database but my jpanel wont update...
I wonder if there is an easy fix for this?
private void DeleteActionPerformed(java.awt.event.ActionEvent evt) {
infLabel.setText(inform[2]);
Connection connection = FlatFinder.getConnection();
Statement selectStmt = null;
try {
selectStmt = connection.createStatement();
Flat activeFlat = (Flat) AdminAll.getSelectedValue();
String sql = String.format(
"DELETE FROM `flats` WHERE flat_id = %d",
activeFlat.getId()
);
selectStmt.executeUpdate(sql);
} catch (SQLException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
this.repaint();
}
This is my current code. Is there any easy solution to update the jpanel when I press the delete button?