Dynamically update values form database against selected index in Combobox - java

Scenario is, There is combobox and 2 textfields. Combobox items (model) are fetched from database and update Combobox dynamically. I have done it.
Now i need to do that when user select any item(model) from Combobox then its name and price should be updated in textfields.
How to do it ?
//This code only have one textfield one i will make after.
public class Purchases extends JFrame {
private JPanel contentPane;
private JTextField textField;
JComboBox comboBox = new JComboBox();
String model, name;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Purchases frame = new Purchases();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Purchases() {
try {
String host;
host = "jdbc:mysql://localhost:3306/sfs_electronics";// [root on Default schema]";
String uName = "root";
String uPass= "";
Connection con = DriverManager.getConnection( host, uName, uPass );
Statement stmt = con.createStatement( );
String SQL = "SELECT * FROM purchases";
ResultSet rs = stmt.executeQuery( SQL );
while(rs.next())
{
model= rs.getString("Model");
name= rs.getString("Name");
comboBox.addItem(model); // Adding Items in ComboBox
System.out.println(model);
}
}
catch(SQLException e){
System.out.println(e);
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 501, 420);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 10, 465, 146);
contentPane.add(panel);
panel.setLayout(null);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int n=comboBox.getSelectedIndex();
System.out.println(n);
System.out.println(comboBox.getSelectedItem());
textField.setText(?????); //Here What i need to code that selected models name should be place here.
}
});
comboBox.setBounds(109, 11, 86, 20);
panel.add(comboBox);
textField = new JTextField();
textField.setBounds(109, 47, 86, 20);
panel.add(textField);
textField.setColumns(10);
}
}

Code will be placed in comboBox.addActionListener.
//Connect database
String s = comboBox.getSelectedItem().toString();
String SQL = "SELECT * FROM `products` WHERE `Model` = '" + s + "'";
ResultSet rs = stmt.executeQuery( SQL );
while(rs.next())
{
requiredtextfield.setText(rs.getString("ColumnNAme_of_database"));
}

You can introduce a class Purchase with all necessary fields from DB you are going to use
public class Purchase {
int id;
String name;
String model;
...
public String toString() {
return model;
}
}
On retrieving data from DB create Purchase instances filling the fields from your result set. Place the purchase items in the combobox. TO provide correct showing you can either add your renderer which shows model field of the item (more complicated) or just override toString() method of Purchase class to return model field.
When somethinf is selected in the combobox the selected item is particular purchase instance and you can use the name field to reflect in the text field.

Related

Sort the JTable by JRadioButton

I want sort the JTable by the JRadioButton component's ActionListener method. When I click "name" the table will sorted out by name. But now I click name radio button, all is blank.
The Main code for query the database all is fine. So I have problem for add another table to the JScrollPane. For the simplicity, I deleted all the import related code. But all the code is working except the radio button's action listener.
public class JtableDemo extends JPanel implements ActionListener {
private static JFrame frame;
JTextField textField;
JScrollPane scrollPanel;
JRadioButton nameButton = new JRadioButton("name");
JRadioButton departmentButton =new JRadioButton("department");
JRadioButton salaryButton =new JRadioButton("Salary");
JRadioButton dateButton = new JRadioButton("date");
ButtonGroup orderbyButtonGroup = new ButtonGroup();
JTable jTable = new JTable();
String orderbyname = "select * from emp where salary >6000 order by name";
String orderbydepartment = "select * from emp where salary >6000 order by department";
String orderbysalary = "select * from emp where salary >6000 order by salary";
public JtableDemo() throws SQLException {
nameButton.addActionListener(this);
departmentButton.addActionListener(this);
salaryButton.addActionListener(this);
dateButton.addActionListener(this);
orderbyButtonGroup.add(nameButton);
orderbyButtonGroup.add(departmentButton);
orderbyButtonGroup.add(salaryButton);
orderbyButtonGroup.add(dateButton);
this.add(nameButton);
this.add(departmentButton);
this.add(salaryButton);
this.add(dateButton);
String query = "select * from emp where salary>? ";
PreparedStatement statement = Main.connection.prepareStatement(query);
statement.setInt(1,6000);
//statement.setString(2,"id");
ResultSet resultSet = statement.executeQuery();
jTable.setModel(DbUtils.resultSetToTableModel(resultSet));
jTable.setPreferredScrollableViewportSize(new Dimension(500,200));
jTable.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(jTable);
add(scrollPane);
String title = "all emp's salary less than 5600";
this.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),title, TitledBorder.CENTER,TitledBorder.TOP));
}
public static void createandShowGUI() throws SQLException {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JtableDemo newContentPane = new JtableDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==nameButton) {
try {
JScrollPane scrollPane = new JScrollPane(jTable);
PreparedStatement orderbystatement = Main.connection.prepareStatement(orderbyname);
//orderbystatement.setString(1,"name");
ResultSet resultSet = orderbystatement.executeQuery();
jTable.setModel(DbUtils.resultSetToTableModel(resultSet));
jTable.setPreferredScrollableViewportSize(new Dimension(500,200));
jTable.setFillsViewportHeight(true);
} catch (SQLException throwables) {
throwables.printStackTrace();
} }
if(e.getSource()==departmentButton) { System.out.println("testdepartmentButton"); }
if(e.getSource()==salaryButton) { System.out.println("testsalaryButton"); }
if(e.getSource()==dateButton) { System.out.println("testdateButton"); }
}
}

refresh a JLabel

This is as the title says, I need your help to refresh the contents of a JLabel.
I explain my worries.
I have a first JFarm or I have a calendar (a DatePicker) which allows me to select a date and a button.
When I click on the button it opens a new window and in this famous window I have my JLabel or I would like to see my date.
In this last window I wrote:
System.out.println(datePicker.getDate());
labelDate.setText(datePicker.getDate());
When I first open my window everything works fine, but if I close it, I change the date in my DatePicker and reopen the window by clicking on my button the date does not change !!!
It always remains on the first date sent.
Yet my:
System.out.println(datePicker.getDate());
Returns the correct date correctly each time.
Do you have an idea ?
Thank you all.
I post my full code but it's very long and not very clean... sorry.
the main window :
public class App extends JFrame{
private JPanel contentPane;
static final int rowMultiplier = 4;
private DatePicker datePicker;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App frame = new App();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public App() throws SQLException{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
this.setTitle("Absences Management");
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
// =================== PanelTitle ===================================
JPanel panelTitle = new JPanel();
contentPane.add(panelTitle, BorderLayout.NORTH);
JLabel labelTitle = new JLabel("Absence Management");
panelTitle.add(labelTitle);
// ================== PanelMenu =====================================
JPanel panelMenu = new JPanel();
contentPane.add(panelMenu, BorderLayout.WEST);
panelMenu.setLayout(new BoxLayout(panelMenu, BoxLayout.Y_AXIS));
// Border and name for the panel
panelMenu.setBorder(BorderFactory.createTitledBorder(" Menu "));
// create buttons and set the actions for the menu
JButton buttonAddClass = new JButton(new ActionButtonClassManagement(this,"Class management"));
JButton buttonQuit = new JButton(new ActionButtonQuit(this," Quit "));
// add different components in the Panel Menu
panelMenu.add(buttonAddClass);
panelMenu.add(buttonQuit);
// ================= PanelCalendar ==================================
JPanel panelCalendar = new JPanel();
contentPane.add(panelCalendar, BorderLayout.CENTER);
panelCalendar.setAlignmentX(CENTER_ALIGNMENT);
// black border for the panel
panelCalendar.setBorder(BorderFactory.createTitledBorder(" Calendar "));
JLabel labelCalendar = new JLabel("CALENDAR :");
panelCalendar.add(labelCalendar);
// ===== create the calendar
// settings
DatePickerSettings dateSettings = new DatePickerSettings();
dateSettings.setVisibleClearButton(false);
// set the current date by default
dateSettings.setAllowEmptyDates(false);
datePicker = new DatePicker(dateSettings);
// create a icon
URL dateImageURL = FullDemo.class.getResource("/img/calendar20x20.png");
Image calendarImage = Toolkit.getDefaultToolkit().getImage(dateImageURL);
ImageIcon calendarIcon = new ImageIcon(calendarImage);
// create button and set the icon
JButton datePickerButton = datePicker.getComponentToggleCalendarButton();
datePickerButton.setText("");
datePickerButton.setIcon(calendarIcon);
// add the calendar to the PanelCalendar
panelCalendar.add(datePicker);
// create a button Show absences
JButton buttonAbsence = new JButton(new ActionButtonAbsences(this,"Absences", datePicker));
//add the button to the panelCalendar
panelCalendar.add(buttonAbsence);
}
}
The class for my button Absence :
public class ActionButtonAbsences extends AbstractAction{
private App windowAbsence;
private DatePicker datePicker = new DatePicker();
private String dateString = new String();
public ActionButtonAbsences(App app, String textButton, DatePicker datePicker) {
// TODO Auto-generated constructor stub
super(textButton);
this.datePicker = datePicker;
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
dateString = datePicker.getText();
WindowAbsence fen = new WindowAbsence(windowAbsence, datePicker, dateString);
}
}
And the window that opens when I press the button Absence :
public class WindowAbsence extends JDialog implements ActionListener{
private static JPanel panelWindow = new JPanel(new BorderLayout());
private JPanel panelTitle = new JPanel();
private JPanel panelWindowLeft = new JPanel();
private JPanel panelWindowRight = new JPanel();
private JComboBox comboBoxClass;
private JComboBox comboBoxStudent;
private DatePicker datePicker;
private JLabel labelDate = new JLabel();
private String dateString = new String();
private ModelTable modelTableAbsence = new ModelTable();
private JTable tableAbsence = new JTable(modelTableAbsence);
public WindowAbsence(Frame frame, DatePicker datePicker, String date){
//super call the constructor of the main window
// the first argument is the mother window
// the second argument disable this window
super(frame,true);
labelDate.setText(datePicker.getText());
this.dateString = date;
// add BorderLayout in this Window
this.setLayout(new BorderLayout());
// name of the window
this.setTitle("Absences");
// size of the window
this.setSize(700, 600);
// effect for the red cross
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.datePicker = datePicker;
// =================== Data bases connection ============================
/**
* download mysql-connector-java-5.1.40.tar.gz
* https://dev.mysql.com/downloads/file/?id=470332
* Clic droit sur le dossier du projet
* Clic right on the folder of the project
* Build Path
* Add external Archive
*/
DataBase database = new DataBase();
String url = "jdbc:mysql://localhost:3306/AbsenceManagement";
String user = "root";
String pass = "";
String driver = "com.mysql.jdbc.Driver";
try {
database.connectionDataBase(url, user, pass, driver);
// ================== PANEL TITLE ==================================
//JLabel labelDate = new JLabel();
panelTitle.add(labelDate);
//labelDate.setText(datePicker.getText());
date = datePicker.getText();
System.out.println("date: "+date);
labelDate.setText(date);
panelWindow.add(panelTitle, BorderLayout.NORTH);
// ================ PANEL LEFT =====================================
panelWindowLeft.setBorder(BorderFactory.createTitledBorder(" Absences "));
// =========== panelComboBoxLabelClass ======================
JPanel panelLabelComboBoxClass = new JPanel();
panelLabelComboBoxClass.setLayout(new BoxLayout(panelLabelComboBoxClass, BoxLayout.LINE_AXIS));
JLabel labelComboBoxClass = new JLabel("Class :");
comboBoxClass = new JComboBox();
comboBoxClass.addItem("");
panelLabelComboBoxClass.add(labelComboBoxClass);
panelLabelComboBoxClass.add(comboBoxClass);
Statement statementClass = DataBase.connection.createStatement();
ResultSet resultClass = statementClass.executeQuery("SELECT class FROM Class");
//receive the MetaData
ResultSetMetaData resultMetaClass = (ResultSetMetaData) resultClass.getMetaData();
// add the data in the row
while(resultClass.next()){
comboBoxClass.addItem(resultClass.getObject(1));
}
comboBoxClass.addActionListener(this);
resultClass.close();
statementClass.close();
// =========== panelComboBoxLabelStudent ======================
JPanel panelLabelComboBoxStudent = new JPanel();
panelLabelComboBoxStudent.setLayout(new BoxLayout(panelLabelComboBoxStudent, BoxLayout.LINE_AXIS));
JLabel labelComboBoxStudent = new JLabel("Student :");
comboBoxStudent = new JComboBox();
panelLabelComboBoxStudent.add(labelComboBoxStudent);
panelLabelComboBoxStudent.add(comboBoxStudent);
// ========== panelComboBoxHour ===============================
int rowMultiplier = 4;
int row = rowMultiplier;
TimePickerSettings timeSettings = new TimePickerSettings();
timeSettings.setDisplayToggleTimeMenuButton(true);
timeSettings.setDisplaySpinnerButtons(false);
JPanel panelComboBoxHour = new JPanel();
panelComboBoxHour.setLayout(new BoxLayout(panelComboBoxHour, BoxLayout.LINE_AXIS));
JLabel labelComboBoxFrom = new JLabel("From :");
panelComboBoxHour.add(labelComboBoxFrom);
TimePicker timePickerFrom = new TimePicker(timeSettings);
timePickerFrom = new TimePicker();
panelComboBoxHour.add(timePickerFrom, getConstraints(1, (row * rowMultiplier), 1));
//panelComboBoxHour.addLabel(panelComboBoxHour, 1, (row++ * rowMultiplier), "Time 1, Default Settings:");
JLabel labelComboBoxTo = new JLabel("To :");
panelComboBoxHour.add(labelComboBoxTo);
TimePicker timePickerTo = new TimePicker();
timePickerTo = new TimePicker();
panelComboBoxHour.add(timePickerTo, getConstraints(1, (row * rowMultiplier), 1));
// ========== panel button add absence ==============
JPanel panelButtonAddAbsence = new JPanel();
panelButtonAddAbsence.setLayout(new BoxLayout(panelButtonAddAbsence, BoxLayout.LINE_AXIS));
JButton buttonAddAbsence = new JButton("Add Absence");
panelButtonAddAbsence.add(buttonAddAbsence);
// ========================================
panelWindowLeft.setLayout(new BoxLayout(panelWindowLeft, BoxLayout.PAGE_AXIS));
panelWindowLeft.add(panelLabelComboBoxClass);
panelWindowLeft.add(panelLabelComboBoxStudent);
panelWindowLeft.add(panelComboBoxHour);
panelWindowLeft.add(panelButtonAddAbsence);
panelWindow.add(panelWindowLeft, BorderLayout.WEST);
// ====================== PANEL RIGHT ================================
panelWindowRight.setBorder(BorderFactory.createTitledBorder(" Absences "));
//=================== TABLE =======================================
Statement statementAbsence = DataBase.connection.createStatement();
// requet SQL
ResultSet resultAbsence;
ResultSetMetaData resultMetaAbsence;
modelTableAbsence.addColumn("Student");
modelTableAbsence.addColumn("Date");
modelTableAbsence.addColumn("To");
modelTableAbsence.addColumn("From");
// requete SQL
resultAbsence = statementAbsence.executeQuery("SELECT * FROM Absence WHERE `dateAbsence`='"+datePicker.getDate().toString()+"'");
//receive the MetaData
resultMetaAbsence = (ResultSetMetaData) resultAbsence.getMetaData();
modelTableAbsence.fireTableDataChanged();
if(!resultAbsence.next()){
System.out.println("null");
}else{
// add the data in the row
do{
modelTableAbsence.addRow(new Object[]{
resultAbsence.getObject(2).toString(),
resultAbsence.getObject(3).toString(),
resultAbsence.getObject(4).toString(),
resultAbsence.getObject(5).toString()
});
}while(resultAbsence.next());
// close the statementClass
statementAbsence.close();
resultAbsence.close();
// ========= replace id student by firstName and lastName
Statement statementNameStudent = DataBase.connection.createStatement();
ResultSet resultNameStudent = null;
int nbRow = modelTableAbsence.getRowCount();
for(int i = 0; i < nbRow; i++){
resultNameStudent = statementNameStudent.executeQuery("SELECT firstName, lastName FROM Student WHERE `id`='"+modelTableAbsence.getValueAt((i), 0)+"'");
// add the data in the row
while(resultNameStudent.next()){
modelTableAbsence.setValueAt(
(resultNameStudent.getObject(1)+" "+resultNameStudent.getObject(2)),i,0);
}
}
statementNameStudent.close();
resultNameStudent.close();
}
// =================================================================
JScrollPane scrollPane = new JScrollPane(tableAbsence);
panelWindowRight.add(scrollPane);
panelWindow.add(panelWindowRight, BorderLayout.CENTER);
this.setContentPane(panelWindow);
this.setVisible(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth) {
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.WEST;
gc.gridx = gridx;
gc.gridy = gridy;
gc.gridwidth = gridwidth;
return gc;
}
// model table for table schedule
public class ModelTableSchedule extends DefaultTableModel {
ModelTableSchedule(Object[][] dataStudent, String[] columnNamesStudent) {
super(dataStudent, columnNamesStudent);
}
// the function return always false, the table is never editable
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
public void actionPerformed(ActionEvent arg0) {
modelTableAbsence.fireTableDataChanged();
// =================== Data bases connection ============================
/**
* download mysql-connector-java-5.1.40.tar.gz
* https://dev.mysql.com/downloads/file/?id=470332
* Clic droit sur le dossier du projet
* Clic right on the folder of the project
* Build Path
* Add external Archive
*/
DataBase database = new DataBase();
String url = "jdbc:mysql://localhost:3306/AbsenceManagement";
String user = "root";
String pass = "";
String driver = "com.mysql.jdbc.Driver";
try {
database.connectionDataBase(url, user, pass, driver);
// add value in ComboBox
Statement statementStudent;
comboBoxStudent.removeAllItems();
statementStudent = DataBase.connection.createStatement();
ResultSet resultStudent = statementStudent.executeQuery("SELECT * FROM `Student` WHERE `class` LIKE '"+comboBoxClass.getSelectedItem().toString()+"'");
//receive the MetaData
ResultSetMetaData resultMetaStudent = (ResultSetMetaData) resultStudent.getMetaData();
// add the data in the row
while(resultStudent.next()){
comboBoxStudent.addItem((resultStudent.getObject(2)+" "+resultStudent.getObject(3)));
}
comboBoxStudent.revalidate();
resultStudent.close();
statementStudent.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thank you for your help.
Again me,
I found my error !
In my WindowAbsence :
private static JPanel panelWindow = new JPanel(new BorderLayout());
The panel it was in static...
i hope will serve for someone !

I need to add another column in my database but I don't know how to

I want to add another column in mysql either by using java or manually in the mysql application. This is my java code and I need to add a column named book_id
package liblog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class AStudents extends JFrame {
private JTextField admissionnumber;
private JTextField firstname;
private JTextField lastname;
private JTextField surname;
private JTextField house;
private JTextField dome;
private JButton add;
private JButton back;
private static Connection conn;
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon("C:/Users/User/workspace/Login/src/liblog/parklands.png");
JPanel panel = new JPanel(new GridBagLayout());
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JLabel admissionNumber = new JLabel();
JLabel firstName = new JLabel();
JLabel lastName = new JLabel();
JLabel surName = new JLabel();
JLabel mainHouse = new JLabel();
JLabel mainDome = new JLabel();
AStudents(){
super("DR.RIBEIRO PARKLANDS SCHOOL");
setLayout(new FlowLayout(FlowLayout.LEFT,3,100));
setBounds(500,500,550,550);
setLocation(500,200);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container con = this.getContentPane();
con.setBackground(Color.GRAY);
con.add(panel);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
panel2.setLayout(new FlowLayout(FlowLayout.CENTER,3,10));/*X axis,Y axis*/
panel3.setLayout(new BoxLayout(panel,BoxLayout.LINE_AXIS));
panel.setBackground(Color.GRAY);
/* admissionNumber=new JLabel("Admission Number");
admissionNumber.setAlignmentX(0.0f);
admissionnumber = new JTextField("No",30);
admissionnumber.setAlignmentX(0.0f);*/
firstName=new JLabel("First Name");
firstName.setAlignmentX(0.0f);
firstname = new JTextField("Name",20);
firstname.setAlignmentX(0.0f);
lastName=new JLabel("Last Name");
lastName.setAlignmentX(0.0f);
lastname = new JTextField("Name",20);
lastname.setAlignmentX(0.0f);
surName=new JLabel("Surname");
surName.setAlignmentX(0.0f);
surname = new JTextField("Name",20);
surname.setAlignmentX(0.0f);
mainHouse=new JLabel("House");
mainHouse.setAlignmentX(0.0f);
house = new JTextField("House",20);
house.setAlignmentX(0.0f);
mainDome=new JLabel("Dome");
mainDome.setAlignmentX(0.0f);
dome = new JTextField("Dome",20);
dome.setAlignmentX(0.0f);
add = new JButton("Add Student");
back = new JButton("Back");
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Insert into SQL:
try {
PreparedStatement insert = conn.prepareStatement("INSERT INTO students (first_name, last_name, surname, house, dome) VALUES (?,?,?,?,?)");
insert.setString(1, firstname.getText());
insert.setString(2, lastname.getText());
insert.setString(3, surname.getText());
insert.setString(4, house.getText());
insert.setString(5, dome.getText());
insert.execute();
ABooks abooks = new ABooks();
dispose();
}
catch(Exception ex) {
System.out.println(ex);
}
}
});
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Admin admin = new Admin();
dispose();
}
});
//panel.add(admissionNumber);
//panel.add(admissionnumber);
panel.add(firstName);
panel.add(firstname);
panel.add(lastName);
panel.add(lastname);
panel.add(surName);
panel.add(surname);
panel.add(mainHouse);
panel.add(house);
panel.add(mainDome);
panel.add(dome);
panel.add(add);
panel.add(back);
try {
conn = getConnection();
createTable();
}
catch(Exception ex) {
System.out.println(ex);
}
setVisible(true);
}
/*public static void main(String[]args) throws Exception{new AStudents();
createTable();
}*/
//Table
public static void createTable() throws Exception{
try{
Connection conn = getConnection();
PreparedStatement create = conn.prepareStatement("CREATE TABLE IF NOT EXISTS students(id int NOT NULL AUTO_INCREMENT,first_name varchar(45),last_name varchar(45),surname varchar(320),house varchar(50),dome varchar(50),book_id varchar(50),PRIMARY KEY(id))");
create.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally {
System.out.println("System Updated");};
}
//EndofTable
//DB
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/students?useSSL=false";
String username = "root";
String password = "toor";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
}catch(Exception e){
System.out.println(e);
}
return null;
}
//DB
}
The application is giving me the following error which I cannot get rid of
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'borrow_id' in 'field list'
This is the other code http://www.rapidtables.com/tools/notepad.htm
In your SQL DB:
ALTER TABLE students ADD book_id varchar(50)
I'm guessing as to the datatype of the book_id.
Do you mean book_id or borrow_id? I don't see borrow_id in your code which is somewhat confusing and probably why you're getting down voted.

Trying to connect to a sqlite but: SQL error or missing database (no such table: Bank_001)

I don't know what is wrong with this code; the SQL commands and the path looks alright. The connect to the db is ok; but when I try to pass a simple search; it returns that that table doesn't exist.
I tried it (the same code) in a different method to add data and it works fine; so I don't know what I'm doing wrong.
Thanks for your attention.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
First_GUI frame = new First_GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conn = null; //Call the Connection Class from JavaSqlite Class
/**
* Create the frame.
*/
public First_GUI() {
conn = Sqlite_Connection.dbconnector(); //call the connection CONN from SQLite class, method DBconnector.
setTitle("First GUI App");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(panel, BorderLayout.NORTH);
JLabel lblEnterTheName = new JLabel("Enter the Name :");
lblEnterTheName.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblEnterTheName.setVerticalAlignment(SwingConstants.TOP);
lblEnterTheName.setHorizontalAlignment(SwingConstants.LEFT);
panel.add(lblEnterTheName);
NameField = new JTextField();
panel.add(NameField);
NameField.setColumns(10);
JButton Search = new JButton("Search");
Search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// ****************************************************************
// Here is the PROBLEM.
String sql = "SELECT * FROM Bank_001 where AccountName like ?";
try {
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, NameField.getText());
ResultSet rs = pst.executeQuery();
rs.close();
pst.close();
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
});
panel.add(Search);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextPane textPane = new JTextPane();
textPane.setFont(new Font("Tahoma", Font.PLAIN, 14));
scrollPane.setViewportView(textPane);
}
}
can you show the code for this ?
conn = Sqlite_Connection.dbconnector();
are you using setURL() on a new SQLiteDataSource ?
assuming using setURL, is it constructed correctly ?
Something like:
"jdbc:sqlite:sqlite-test.db"

Insert data to a table via Java GUI

I am getting a bunch of error when I try to insert a new data to the table (Type data for each field and then click submit). It supposed to output the SQL insertion command (exactly the same on that used by Java) in the TextArea. How can I fix this problem? Am I missing something in my code? Here is my code:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
//This GUI interface is a place holder to be finished by students.
public class InsertPanel extends JPanel{
private Connection connection = null;
private Statement statement = null;
public JTextField isbnTextFld;
public JTextField authorTextFld;
public JTextField titleTextFld;
public JTextField priceTextFld;
public JTextArea textArea;
public JButton submitBtn;
public InsertPanel() {
setBackground(Color.yellow);
setPreferredSize(new Dimension(540, 500));
JPanel p = new JPanel();
p.setLayout(new GridLayout(5, 3));
JLabel isbnLabel = new JLabel("ISBN: ");
isbnTextFld = new JTextField(10);
JLabel authorLabel = new JLabel("Author: ");
authorTextFld = new JTextField(15);
JLabel titleLabel = new JLabel("Title: ");
titleTextFld = new JTextField(20);
JLabel priceLabel = new JLabel("Price: ");
priceTextFld = new JTextField(10);
submitBtn = new JButton("Submit");
ButtonListener buttonListener = new ButtonListener();
submitBtn.addActionListener(buttonListener);
textArea = new JTextArea(10, 30);
p.add(isbnLabel);
p.add(isbnTextFld);
p.add(authorLabel);
p.add(authorTextFld);
p.add(titleLabel);
p.add(titleTextFld);
p.add(priceLabel);
p.add(priceTextFld);
p.add(submitBtn);
p.add(textArea);
add(p, BorderLayout.NORTH);
add(textArea, BorderLayout.CENTER);
}
public class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
try {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost/books", "root", "admin");
statement = connection.createStatement();
String isbn = isbnTextFld.getText();
String title = titleTextFld.getText();
String author = authorTextFld.getText();
String price = priceTextFld.getText();
String sql = "Insert('" + (isbn) + "' + '" + (title) + "' + '" + (author) + "' + '" + (price)
+ "')";
statement.executeUpdate(sql);
} catch (SQLException sqlException){
sqlException.printStackTrace();
}
}
}
}
create table books
( isbn char(13) not null primary key,
author char(30),
title char(60),
price float(4,2)
);
insert into books values
("0-672-31697-8", "Michael Morgan", "Java 2 for Professional Developers", 34.99),
("0-672-31745-1", "Thomas Down", "Installing Debian GNU/Linux", 24.99),
("0-672-31509-2", "Pruitt, et al.", "Teach Yourself GIMP in 24 Hours", 24.99),
("0-672-31769-9", "Thomas Schenk", "Caldera OpenLinux System Administration Unleashed", 49.99);
Thanks for your hepl!!!
My first suggestion is that you should learn more SQL Syntax before attempting further. I am stating this because the valid SQL insert statement should look like:
INSERT INTO <table_name> VALUES (<value1>, <value2>, ....);
OR
INSERT INTO <table_name> (<column_1>, <column_2>, ...) VALUES (<value1>, <value2>, ....);
Also you should try to use PreparedStatement instead of Statement to dynamically set the values to the statement. And go through JDBC in details.

Categories