How can I fill a combobox with values in a database? - java

how to insert a combobox with values ​​from the data base
I want to select from the database and add in the combobox
I have two class:
constructor Database() first class
//constructeur
Database()
{
void remplir_Jcomb() {
Connection conn = null;
Statement st = null;
String rq1 = "SELECT region FROM rg";
String rq2 = "SELECT ACTELS FROM rg";
// - Paramètres de connexion à la base de données
String url = "jdbc:mysql://localhost/réseau";
String login = "root";
String password = "";
String driver = "com.mysql.jdbc.Driver";
try {
//comboBox_gouver.removeAllItems();
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,login,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
st = conn.createStatement();
ResultSet rs1 = st.executeQuery(rq1);
ResultSet rs2 = st.executeQuery(rq2);
while ((rs1.next())&&(rs2.next())) {
comboBox_gouver.addItem(rs1.getString(1));
comboBox_ACTELS.addItem(rs2.getString(1));
}
st.close();
rs1.close();
rs2.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();}
}
}
interface swing second class which contains two JComboBox
call constructor Database()
private Database BD= new Database();
public Region() {
//first JComboBox
comboBox_gouver = new JComboBox<String>();
BD.remplir_Jcomb();
sl_contentPanel.putConstraint(SpringLayout.NORTH, lbl_gouver, 5, SpringLayout.NORTH, comboBox_gouver);
sl_contentPanel.putConstraint(SpringLayout.NORTH, comboBox_gouver, 5, SpringLayout.NORTH, contentPanel);
sl_contentPanel.putConstraint(SpringLayout.WEST, comboBox_gouver, 16, SpringLayout.EAST, lbl_gouver);
sl_contentPanel.putConstraint(SpringLayout.EAST, comboBox_gouver, -26, SpringLayout.EAST, contentPanel);
contentPanel.add(comboBox_gouver);
comboBox_ACTELS = new JComboBox<String>();
sl_contentPanel.putConstraint(SpringLayout.NORTH, lbl_ACTELS, 5, SpringLayout.NORTH, comboBox_ACTELS);
sl_contentPanel.putConstraint(SpringLayout.NORTH, comboBox_ACTELS, 6, SpringLayout.SOUTH, comboBox_gouver);
sl_contentPanel.putConstraint(SpringLayout.WEST, comboBox_ACTELS, 90, SpringLayout.EAST, lbl_ACTELS);
sl_contentPanel.putConstraint(SpringLayout.SOUTH, comboBox_ACTELS, -29, SpringLayout.SOUTH, contentPanel);
sl_contentPanel.putConstraint(SpringLayout.EAST, comboBox_ACTELS, -26, SpringLayout.EAST, contentPanel);
contentPanel.add(comboBox_ACTELS);
}}
erreur:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7139)
at tn.pack.ACTEL.Database.remplir_Jcomb(Database.java:94)
at tn.pack.ACTEL.Region.<init>(Region.java:75)
at tn.pack.ACTEL.Region.main(Region.java:41)

1) fill data from Db (use finally block for closing opened Objects, because this code is executed in all cases)
void whatever {
Connection conn = null;
Statement st1 = null;
try {
st1 = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
st1.close();
rs1.close();
rs2.close();
conn.close();
} catch (SQLException ex) {
//
}
}
}
2) inside Db Statement fill data to the (notice difference in API betweens Java6 / Java7),
to the ComboBoxModel - JComboBox(ComboBoxModel aModel)/JComboBox(ComboBoxModel<E> aModel)
to the arrays of Objects/Elements - JComboBox(Object[] items)/JComboBox(E[] items)
to the Vector of Objects/Elements - JComboBox(Vector items)/JComboBox(Vector<E> items)
if Sql block ended then add array type to the JComboBox
EDIT:
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class ComboBoxListeners {
private JFrame f;
private JComboBox comboBox;
private JLabel label = new JLabel();
private DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel();
public ComboBoxListeners() {
comboBox = new JComboBox(comboBoxModel);
comboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if ((e.getStateChange() == ItemEvent.SELECTED)) {
String str = comboBox.getSelectedItem().toString();
label.setText("Selected Value From JComboBox is : " + str);
}
}
});
label.setPreferredSize(new Dimension(400, 30));
JButton btnAdd = new JButton(new AbstractAction("Append Items") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
addNewItemsFromDatabase();
}
});
JButton btnRefresh = new JButton(new AbstractAction("Refresh Items") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
refreshItemsFromDatabase();
}
});
f = new JFrame("ComboBox ItemListeners");
f.setLayout(new GridLayout(0, 1, 15, 15));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(comboBox);
f.add(label);
f.add(btnAdd);
f.add(btnRefresh);
f.setLocation(150, 150);
f.pack();
f.setVisible(true);
}
public void addNewItemsFromDatabase() {
ArrayList<Integer> ageList = new ArrayList<Integer>();
for (int i = 1; i <= 5; ++i) {
ageList.add(i);
}
for (final Integer i : ageList) {
EventQueue.invokeLater(new Runnable() {
public void run() {// updates to the Swing GUI must be done on EDT
comboBoxModel.addElement(i);
}
});
}
}
public void refreshItemsFromDatabase() {
comboBoxModel = new DefaultComboBoxModel();
ArrayList<Integer> ageList = new ArrayList<Integer>();
for (int i = 1; i <= 5; ++i) {
ageList.add(i);
}
for (final Integer i : ageList) {
EventQueue.invokeLater(new Runnable() {
public void run() {// updates to the Swing GUI must be done on EDT
comboBoxModel.addElement(i);
}
});
}
comboBox.setModel(comboBoxModel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ComboBoxListeners comboBoxListeners = new ComboBoxListeners();
}
});
}
}

Use two separate Statement objects for the two ResultSet objects. You cannot reuse a Statement object when it is already open and used by a ResultSet. Something like this:-
void remplir_Jcomb() {
Connection conn = null;
Statement st1 = null;
Statement st2 = null;
String rq1 = "SELECT region FROM rg";
String rq2 = "SELECT ACTELS FROM rg";
//Rest of your code here
try {
// snipping off some more code
//...
st1 = conn.createStatement();
st2 = conn.createStatement();
ResultSet rs1 = st1.executeQuery(rq1);
ResultSet rs2 = st2.executeQuery(rq2);
while ((rs1.next())&&(rs2.next())) {
comboBox_gouver.addItem(rs1.getString(1));
comboBox_ACTELS.addItem(rs2.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
finally{
st1.close();
st1.close();
rs1.close();
rs2.close();
conn.close();
}
}

Related

How to make data insertion, modification, deletion, and search by pressing the j button in the jdbc program?

I tried to implement an event when the button is pressed by attaching an action listener to the insert, edit, delete, and search buttons.
It seems that the data in the database is not properly inserted, modified, deleted, or searched because of the wrong data manipulation language.
And I want to output the result of manipulating the database data in JTextArea.
How to modify the source code?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
import java.util.*;
public class MovieManagement extends JFrame {
Container c = this.getContentPane();
public teamMovie2() {
this.setSize(500, 400);
this.setTitle("movie");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setDesign();
this.setVisible(true);
}
// gui
private void setDesign() {
c.setLayout(new BorderLayout());
JPanel pTop = new JPanel(new GridLayout(0, 1));
JPanel p1 = new JPanel(new FlowLayout());
JPanel p2 = new JPanel(new FlowLayout());
JPanel p3 = new JPanel(new FlowLayout());
JPanel p4 = new JPanel(new FlowLayout());
JPanel p5 = new JPanel(new FlowLayout());
// p1
JLabel title = new JLabel("title");
JTextField title_tf = new JTextField(20);
p1.add(title);
p1.add(title_tf);
// p2
JLabel director = new JLabel("director");
JTextField director_tf = new JTextField(20);
JLabel genre = new JLabel("genre");
String[] combGName = { "all", "action", "comedy", "drama", "melo", "horror/thriller", "SF/fantasy", "animation" };
JComboBox<String> combG = new JComboBox<String>(combGName);
JLabel time = new JLabel("time");
String[] combTName = {"all", "within 1hour", "within an hour and a half", "within 2hours", "within two and a half hours"};
JComboBox<String> combT = new JComboBox<String>(combTName);
JLabel mainActor = new JLabel("mainActor");
JTextField mainActor_tf = new JTextField(20);
JLabel rating = new JLabel("rating");
String[] combRName = { "all", "r12", "r15", "r18" };
JComboBox<String> combR = new JComboBox<String>(combRName);
JLabel country = new JLabel("country");
String[] combCName = { "all", "america", "asia", "west" };
JComboBox<String> combC = new JComboBox<String>(combCName);
p2.add(director);
p2.add(director_tf);
p2.add(genre);
p2.add(combG);
p2.add(time);
p2.add(combT);
p2.add(mainActor);
p2.add(mainActor_tf);
p2.add(rating);
p2.add(combR);
p2.add(country);
p2.add(combC);
// p3
JButton btn1 = new JButton("insert");
JButton btn2 = new JButton("update");
JButton btn3 = new JButton("delete");
p3.add(btn1);
p3.add(btn2);
p3.add(btn3);
// p4
JTextArea ta = new JTextArea(10, 40);
Border border = BorderFactory.createLineBorder(Color.BLACK);
ta.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(5, 5, 5, 5)));
p4.add(new JScrollPane(ta));
// p5
JButton seb = new JButton("search");
p5.add(seb);
// add panel to contentpane
pTop.add(p1);
pTop.add(p2);
pTop.add(p3);
c.add(pTop, BorderLayout.NORTH);
c.add(p4, BorderLayout.CENTER);
c.add(p5, BorderLayout.SOUTH);
// data insert
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton btn1 = (JButton)e.getSource();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/movie_db?serverTimezone=Asia/Seoul","root","1234");
String sql = "INSERT INTO management VALUES (?,?,?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.executeUpdate();
}
catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
// data update
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton btn2 = (JButton)e.getSource();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/movie_db?serverTimezone=Asia/Seoul","root","1234");
String sql = "UPDATE management SET WHERE";
PreparedStatement ps = con.prepareStatement(sql);
ps.executeUpdate();
}
catch (ClassNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
});
// data delete
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton btn3 = (JButton)e.getSource();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/movie_db?serverTimezone=Asia/Seoul","root","1234");
String sql = "DELETE FROM management WHERE";
PreparedStatement ps = con.prepareStatement(sql);
ps.executeUpdate();
}
catch (ClassNotFoundException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
} catch (SQLException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
}
});
// data search
btn4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton btn4 = (JButton)e.getSource();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/movie_db?serverTimezone=Asia/Seoul","root","1234");
String sql = "SELECT * FROM management";
PreparedStatement ps = con.prepareStatement(sql);
ps.executeUpdate();
}
catch (ClassNotFoundException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
} catch (SQLException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
}
});
}
// VO
class MovieModel {
String title;
String director;
String mainActor;
String[] genre = { "all", "action", "comedy", "drama", "melo", "horror/thriller", "SF/fantasy", "animation" }; // genre
String[] time = {"all", "within 1hour", "within an hour and a half", "within 2hours", "within two and a half hours" }; // running time
String[] rating = { "all", "r12", "r15", "r18" }; // firm rating
String[] country = { "all", "america", "asia", "west" }; // country
MovieModel(String title, String director, String[] genre, String[] time, String main_actor, String[] rating,
String[] country) {
this.title = title;
this.director = director;
this.genre = genre;
this.time = time;
this.mainActor = main_actor;
this.rating = rating;
this.country = country;
}
public class MovieDAO {
Connection con = null;
Statement stmt = null;
PreparedStatement ps = null;
ResultSet rs = null;
// DB connect
public Connection makeConnection() {
String url = "jdbc:mysql://localhost/movie_db?serverTimezone=Asia/Seoul";
String id = "root";
String password = "1234";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("drive loading success");
con = DriverManager.getConnection(url, id, password);
System.out.println("Database connection successful");
} catch (ClassNotFoundException e) {
System.out.println("Driver not found");
e.getStackTrace();
} catch (SQLException e) {
System.out.println("Connection failed");
System.out.println("SQLEXception" + e.getMessage());
System.out.println("SQLState" + e.getSQLState());
System.out.println("VendorError" + e.getErrorCode());
}
return con;
}
/* DB close */
public void disConnection() {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (ps != null)
ps.close();
if (con != null)
con.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
}
public static void main(String[] args) {
new MovieManagement();
}
}
I googled mysql data manipulation language.

ResultSet disappears after updating rows

The only thing remotely similar to my issue that I could find was this, however his problem seemed to be from a user error.
Reset cursor position after ResultSet updateRow
My problem is the following: After updating a row I am not able to access any other rows in my ResultSet. The update itself works fine, but if I want to continue I have to restart the application.
Here's the code:
package database;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Gui extends MyDB {
JFrame f;
JLabel FName;
JLabel LName;
JLabel Age;
JTextField t;
JTextField t2;
JTextField t3;
JButton next = new JButton("next");
JButton update = new JButton("Update");
public Gui() {
frame();
start();
btnAction();
}
public void frame() {
f = new JFrame();
f.setVisible(true);
f.setSize(680, 480);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FName = new JLabel("Name");
LName = new JLabel("Anrede");
Age = new JLabel("age");
t = new JTextField(10);
t2 = new JTextField(10);
t3 = new JTextField(10);
JPanel p = new JPanel();
p.add(FName);
p.add(t);
p.add(LName);
p.add(t2);
p.add(Age);
p.add(t3);
p.add(b1);
p.add(update);
public void btnAction() {
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
});
update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String FName = t.getText();
String LName = t2.getText();
String Age = t3.getText();
try {
System.out.println(rs.getRow());
rs.updateString("FName", FName);
rs.updateString("LName", LName);
rs.updateString("Age", Age);
rs.updateRow();
//System.out.println(rs.getString("FName"));
System.out.println(rs.getRow());
JOptionPane.showMessageDialog(null, "Record updated ");
} catch (Exception ex) {
System.out.println("no");
}
}
});
}
public void start() {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
}
Also:
package database;
import java.sql.*;
public class MyDB {
Connection con;
Statement st;
ResultSet rs;
public MyDB() {
connect();
}
public void connect() {
try {
String db = "jdbc:ucanaccess://Datenbank1.accdb";
con = DriverManager.getConnection(db);
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "select * from Tabelle1";
rs = st.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace(System.out);
}
}
public static void main(String[] args) {
new Gui();
}
}
Output of System.out.println(rs.getRow()); is '0'.
If I want to click on the 'next' button after updating, the message "no next records" is displayed.
I have tried using rs.first(), rs.beforeFirst() and rs.isBeforeFirst(), none of which have worked.
If it helps, I am following this tutorial, which does not run into the same problem:
https://www.youtube.com/watch?v=NPV2o6YjP10

nullpointer exception on table.getSelectedRow()

I have a class A and a class B.
In class A there is a constructor:
public A() {
getSelectedRow();
}
This constructor calls:
public int getSelectedRow() {
System.out.println("The row is : " + table.getSelectedRow());
return table.getSelectedRow();
}
Up to here everything works fine!
The class B then calls the method getSelectedRow() like that:
A results = new A();
System.out.println("YEAH! IT'S: " + results.getSelectedRow());
I just want to find out the selected table row from class A. The problem is that I am getting a null pointer exception and i dont know why. if I dont call the method everything works fine.
CLASS A:
public class AllResultsFromDB extends JFrame {
#SuppressWarnings("compatibility:9056676689615464658")
private static final long serialVersionUID = 188850508334531506L;
GUI ins = new GUI();
JTable table;
public AllResultsFromDB(GUI x) {
final Vector columnNames = new Vector();
final Vector data = new Vector();
this.ins = x;
try {
/** Initializing GUI class
* in order to call
* getSelectedTable() method. **/
Login sgui = new Login();
String dburl = "jdbc:oracle:thin:#localhost:1521:ORCL";
Connection connection = DriverManager.getConnection(dburl, sgui.getUsername(), sgui.getPassword());
// Fetch data from table specified by user
String query = "SELECT * FROM " + ins.getSelectedTable() + " ORDER BY id";
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet rset = stmt.executeQuery(query);
ResultSetMetaData metad = rset.getMetaData();
int columns = metad.getColumnCount();
// This loop gets the names of the columns
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metad.getColumnName(i));
}
// This loop gets the data inside the rows
while (rset.next()) {
final Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rset.getObject(i));
}
data.addElement(row);
}
rset.close();
stmt.close();
connection.close();
// Create table with results
table = new JTable(data, columnNames) {
public boolean isCellEditable(int row, int col) {
return false;
}
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object obj = getValueAt(row, column);
if (obj != null) {
return obj.getClass();
}
}
return Object.class;
}
};
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.SOUTH);
table.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseReleased(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseEntered(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseExited(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseClicked(MouseEvent e) {
getSelectedRow();
if (e.getClickCount() == 2) {
//System.out.println(table.getSelectedRow());
Profile profile = new Profile();
try {
profile.getData();
//wait(500000);
profile.getImage();
} catch (Exception f) {
}
profile.setVisible(true);
}
}
});
} catch (SQLException e) {
}
}
public AllResultsFromDB(int x) {
x = getSelectedRow();
System.out.println(table.getSelectedRow());
}
public int getSelectedRow() {
System.out.println("The row is : " + table.getSelectedRow());
return table.getSelectedRow();
}
}
CLASS B:
public class Profile extends JFrame {
AllResultsFromDB results = new AllResultsFromDB();
public Profile(AllResultsFromDB x) {
this.results=x;
try {
getData();
getImage();
} catch (Exception e) {
e.printStackTrace();
}
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
public void getImage() throws Exception {
JLabel label;
Image img;
ImageIcon pic;
JPanel panel;
img = new ImageIcon("java.jpg").getImage();
pic = new ImageIcon(img);
label = new JLabel("", pic, JLabel.CENTER);
panel = new JPanel(new BorderLayout());
panel.setBounds(new Rectangle(0, 0, 340, 310));
panel.add(label, null);
panel.add(label, BorderLayout.CENTER);
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1148, 336));
this.getContentPane().add(panel, null);
}
public void getData() throws Exception {
String url = "jdbc:oracle:thin:#localhost:1521:ORCL";
String username = "c##lambros";
String password = "16111111";
Connection conn = null;
try {
System.out.println("YEAH! IT'S: " + results.getSelectedRow());
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
String sql = "SELECT foto FROM criminals WHERE id = 5";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
//String name = resultSet.getString(1);
//System.out.println("Name = " + name);
File image = new File("java.jpg");
FileOutputStream fos = new FileOutputStream(image);
byte[] buffer = new byte[256];
//
// Get the binary stream of our BLOB data
//
InputStream is = resultSet.getBinaryStream(1);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
}
private void jbInit() throws Exception {
this.setSize(new Dimension(816, 380));
JLabel label;
Image img;
ImageIcon pic;
JPanel panel;
img = new ImageIcon("java.jpg").getImage();
pic = new ImageIcon(img);
label = new JLabel("", pic, JLabel.CENTER);
panel = new JPanel(new BorderLayout());
panel.setBounds(new Rectangle(0, 0, 340, 310));
panel.add(label, null);
panel.add(label, BorderLayout.CENTER);
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1148, 336));
this.getContentPane().add(panel, null);
}
}
In the classB since you are creating a new instance
A results = new A();
The value present in the table.getSelectedRow() also gets created newly and will point to null.
So make sure that you do somthing
A results = new A(selectedRow);
and in the constructor of the A,pass the argument to the function
getSelectedRow(selectedRow);
Please note : Make sure that the value of the "table.selectedRow" is maintained
If table is your instance variable in Class A then it might not be initialized when you are trying to access it in constructor of A.
And calling getSelectedRow from the constructor is not making any sense too.
Try to initialize the table variable in constructor instead of calling that method, it should work after it.
This is because the table object is not being initialized.
Try to initialize the table object in constructor....it is a good practice

Simple JTable with DefaultTableModel

I use DefaultTableModel for my JTable model, But not show my table!
public class RecordTableGUI2 extends JFrame {
JTable table;
RecordTableModel2 model2;
public RecordTableGUI2() {
model2 = new RecordTableModel2();
table = new JTable(model2);
add(new JScrollPane(table), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RecordTableGUI2();
}
});
}
}
Model Class:
public class RecordTableModel2 extends DefaultTableModel {
Connection con;
Statement statement;
ResultSet result;
String dbUrl = "jdbc:mysql://localhost/mydb";
String query = "Select * from mytable";
Vector data = new Vector();
Vector column = new Vector();
public RecordTableModel2() {
try {
con = DriverManager.getConnection(dbUrl, "root", "2323");
statement = con.createStatement();
result = statement.executeQuery(query);
int c = result.getMetaData().getColumnCount();
for (int i = 1; i <= c; i++) {
column.add(result.getMetaData().getColumnName(i));
System.out.println(result.getMetaData().getColumnName(i)); //prints correct
}
while (result.next()) {
Vector eachRow = new Vector(c);
for (int i = 1; i <= c; i++) {
eachRow.add(result.getString(i));
System.out.println(result.getString(i)); //prints correct
}
data.add(eachRow);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
if (statement != null) {
statement.close();
}
} catch (SQLException sqlee) {
sqlee.printStackTrace();
}
}
}
}
How to introduce vectors to DefaultTableModel?
Output just show a blank JFrame
Add this at first statement of constructor:
super(data,column);
And declare data and column as static

this code shows no error but i am not able to insert the values in database [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.*;
public class TTShow extends JFrame implements ActionListener {
String item1;
JPanel Left, Right, Up, Down, Cntr;
JButton clos, hlp, add;
String str;
WizardSub frm_tch;
JComboBox subj;
String sub_code;
String sub_name;
int lpw;
int dur;
static DBInfo objj0, objj1, objj2, objj3, objj4, objj5, objj6;
static Statement st0, st1, st2, st3, st5, st6;
PreparedStatement pstmt4;
static ResultSet rs0, rs1, rs2, rs3, rs5;;
static Connection cn0, cn1, cn2, cn3, cn4, cn5, cn6;
static String str1;
private JTable table;
public static Vector rows() {
Vector data = new Vector();
String sql = "select * from tt";
try {
objj0 = new DBInfo();// 0
cn0 = objj0.getCon();
st0 = cn0.createStatement();
rs0 = st0.executeQuery(sql);
ResultSetMetaData md = rs0.getMetaData();
int columns = md.getColumnCount();
while (rs0.next()) {
Vector row = new Vector(columns);
for (int i = 2; i <= columns; i++) {
row.addElement(rs0.getObject(i));
}
data.addElement(row);
}
rs0.close();
st0.close();
cn0.close();
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getStackTrace());
}
return data;
}
public static Vector columns()
{
Vector cols = new Vector();
String sql2 = "select * from tt";
try {
objj1 = new DBInfo();// 1
cn1 = objj1.getCon();
st1 = cn1.createStatement();
rs1 = st1.executeQuery(sql2);
ResultSetMetaData md = rs1.getMetaData();
int columns = md.getColumnCount();
for (int i = 2; i <= columns; i++) {
cols.addElement(md.getColumnName(i));
}
rs1.close();
st1.close();
cn1.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getStackTrace());
}
return cols;
}
public TTShow(String title) {
super(title);
setLayout(new BorderLayout());
setSize(900, 600);
setLocationRelativeTo(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
Left = new JPanel();
Left.setLayout(new GridLayout(8, 1, 0, 10));
Right = new JPanel();
Right.setLayout(new GridLayout(12, 1, 0, 20));
Up = new JPanel();
Down = new JPanel();
Cntr = new JPanel();
Cntr.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), ""));
subj = new JComboBox();
String strr = "select * from ttg_sub";
try {
objj2 = new DBInfo();// 2
cn2 = objj2.getCon();
st2 = cn2.createStatement();
rs2 = st2.executeQuery(strr);
while (rs2.next()) {
sub_code = rs2.getString(1);
sub_name = rs2.getString(2);
lpw = rs2.getInt(3);
dur = rs2.getInt(4);
subj.addItem(sub_name);
}
rs2.close();
st2.close();
cn2.close();
}
catch (Exception e) {
}
add = new JButton("add");
add.addActionListener(this);
Left.add(add);
Left.add(subj);
final JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 85, 474, 187);
Cntr.add(scrollPane);
table = new JTable(rows(), columns()); // chargement de JTable
scrollPane.setViewportView(table);
add(Cntr, BorderLayout.CENTER);
add(Left, BorderLayout.WEST);
}
public void getSub(){
String ssq = "select * from ttg_sub";
try {
objj3=new DBInfo();//3
cn3=(Connection) objj3.getCon();
st3 = cn3.createStatement();
rs3 = st3.executeQuery(ssq);
while (rs3.next()) {
sub_code = rs3.getString(1);
sub_name = rs3.getString(2);
lpw = rs3.getInt(3);
dur = rs3.getInt(4);
}
rs3.close();
st3.close();
cn3.close();
}
catch(Exception e){}
}
public void actionPerformed(ActionEvent ls) {
if (ls.getSource() == clos)
{
System.exit(0);
}
else if (ls.getSource() == add)
{
item1 = (String) subj.getSelectedItem();
System.out.print(item1);
String item = item1;
Connection connn;
String ssqs = "insert into tt(I) values(?)";
try {
objj4 = new DBInfo();// 4
cn4 = (Connection) objj4.getCon();
pstmt4 = cn4.prepareStatement(ssqs);
pstmt4.setString(3, item1);
int i = pstmt4.executeUpdate();
System.out.print(i);
pstmt4.close();
cn4.close();
}
catch (Exception e) {
}
}
}
public void putSub() {
Connection conn;
String ssq = "select * from ttg_sub";
try {
objj5 = new DBInfo();// 5
cn5 = (Connection) objj5.getCon();
st5 = cn5.createStatement();
rs5 = st5.executeQuery(ssq);
while (rs5.next()) {
sub_code = rs5.getString(1);
sub_name = rs5.getString(2);
lpw = rs5.getInt(3);
dur = rs5.getInt(4);
}
rs5.close();
st5.close();
cn5.close();
}
catch (Exception e) {
}
}
public void setSub() {
Connection connn;
String ssq = "insert into tt(I) values(item1)";
try {
objj6 = new DBInfo();// 6
cn6 = (Connection) objj6.getCon();
st6 = cn6.createStatement();
st6.close();
st6.close();
cn6.close();
}
catch (Exception e) {
}
}
public static void main(String args[])
{
try {
TTShow dialog = new TTShow(str1);
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
You currently have
String ssqs = "insert into tt(I) values(?)";
pstmt4 = cn4.prepareStatement(ssqs);
pstmt4.setString(3, item1);
but PreparedStatement parameter indices start at 1 so you would need:
pstmt4.setString(1, item1);
Related to that, don't make database calls in the EDT as they'll block that thread. Use a SwingWorker instead. Here is an example

Categories