how to retrieve image from oracle and display in java frame - java

how to retrieve image from oracle and display in java frame. Please send me a sample program
I'm using oracle 10G express edition.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
#SuppressWarnings("serial")
public class Search extends JFrame implements ActionListener {
//Initializing Components
private JLabel lb, lb1, lb2, lb3, lb4, lb5, lb6;
private JTextField tf1, tf2, tf3, tf4, tf5;
private byte s4;
private JButton btn;
private Connection con;
Search() {//Creating Constructor for initializing JFrame components
//Providing Title
super("Fetching Student Information");
lb5 = new JLabel("Enter the Employee id:");
lb5.setBounds(20, 20, 100, 20);
tf5 = new JTextField(20);
tf5.setBounds(130, 20, 200, 20);
btn = new JButton("Submit");
btn.setBounds(50, 50, 100, 20);
btn.addActionListener(this);
lb = new JLabel("Fetching Employee Information From Database");
lb.setBounds(30, 80, 450, 30);
lb.setForeground(Color.red);
lb.setFont(new Font("Serif", Font.BOLD, 20));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lb1 = new JLabel("EmployeeName:");
lb1.setBounds(20, 120, 100, 20);
tf1 = new JTextField(50);
tf1.setBounds(130, 120, 200, 20);
lb2 = new JLabel("Gender:");
lb2.setBounds(20, 150, 100, 20);
tf2 = new JTextField(100);
tf2.setBounds(130, 150, 200, 20);
lb3 = new JLabel("DOB:");
lb3.setBounds(20, 180, 100, 20);
tf3 = new JTextField(50);
tf3.setBounds(130, 180, 200, 20);
lb4 = new JLabel("DOJ:");
lb4.setBounds(20, 210, 100, 20);
tf4 = new JTextField(50);
tf4.setBounds(130, 210, 100, 20);
lb6 = new JLabel("Photo:");
lb6.setBounds(550, 10, 100, 100);
setLayout(null);
setVisible(true);
//Add components to the JFrame
add(lb5);
add(tf5);
add(btn);
add(lb);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
add(lb4);
add(tf4);
add(lb6);
//Set TextField Editable False
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
tf4.setEditable(false);
}
public void actionPerformed(ActionEvent e) {
//Create DataBase Coonection and Fetching Records
try {
String str = tf5.getText();
String url = "jdbc:oracle:thin:#localhost:1521:XE";
String u = "ems2";
String p = "ems2";
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url, u, p);
PreparedStatement st = con.prepareStatement("select * from employee where emp_id=?",);
st.setString(1, str);
//Excuting Query
ResultSet rs = st.executeQuery();
if (rs.next()) {
String s = rs.getString("employeename");
String s1 = rs.getString("dob");
String s2 = rs.getString("gender");
String s3 = rs.getString("doj");
//Sets Records in TextFields.
tf1.setText(s);
tf2.setText(s2);
tf3.setText(s1);
tf4.setText(s3);
} else {
JOptionPane.showMessageDialog(null, "please check your employeeID");
}
PreparedStatement ps1 = con.prepareStatement("select * from photo where photoid =?");
ResultSet rs1 = ps1.executeQuery();
while (rs.next()) {//now on 1st row
Blob b = rs.getBlob(2);//2 means 2nd column data
byte barr[] = b.getBytes(1, (int) b.length());//1 means first image
}
//Create Exception Handler
} catch (Exception ex) {
System.out.println(ex);
}
}
//Running Constructor
public static void main(String args[]) {
new Search();
}
}

Call a query to retrieve image and use something like this.
byte[] imgData = null;
if (rs.next ())
{
Blob img = rs.getBlob(1);
imgData = img.getBytes(1,(int)img.length());
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imgData));
yourJLabelInstance.setIcon(new ImageIcon(image));
}
The yourJLabelInstance is a JLabel created and added to your frame.

Related

incorrect value from java being inserted into mysql

I have a simple program that takes in info for a car sale and enters it in the MySQL DB, everything inserts 100% properly, except the commission integer. It constantly inserts a constant number, never the 'comm' value I have it set to enter. I have the print statement show the correct value but when i check the DB it's not the correct value. I'm not sure if there's a bug on my end or a JDBC thing?
I've entered a simple value of 1, the print statement reads one but the db will always show a value like 1400.
Image links: https://imgur.com/apuKB0C https://imgur.com/Kijl9yL
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.util.Random;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
public class Sale {
Connection con;
Statement st;
int rs;
ResultSet rs1;
ResultSet rs2;
boolean rs3;
JFrame frame5;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sale window = new Sale();
window.frame5.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void connect() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/project", "root", "Alesana14");
st = con.createStatement();
} catch (Exception ex) {
}
}
/**
* Create the application.
*/
public Sale() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame5 = new JFrame();
frame5.setBounds(100, 100, 834, 543);
frame5.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame5.getContentPane().setLayout(null);
JLabel lblCreateSale = new JLabel("Create Sale");
lblCreateSale.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
lblCreateSale.setBounds(385, 113, 110, 44);
frame5.getContentPane().add(lblCreateSale);
JLabel label_1 = new JLabel("Model:");
label_1.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_1.setBounds(264, 252, 77, 16);
frame5.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Make:");
label_2.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_2.setBounds(264, 214, 77, 16);
frame5.getContentPane().add(label_2);
JLabel label_4 = new JLabel("Price:");
label_4.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_4.setBounds(264, 294, 77, 16);
frame5.getContentPane().add(label_4);
JLabel label_5 = new JLabel("Color:");
label_5.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_5.setBounds(264, 336, 77, 16);
frame5.getContentPane().add(label_5);
textField = new JTextField();
textField.setColumns(10);
textField.setBounds(353, 210, 185, 26);
frame5.getContentPane().add(textField);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(353, 248, 185, 26);
frame5.getContentPane().add(textField_1);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(353, 284, 185, 26);
frame5.getContentPane().add(textField_3);
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String id = textField_6.getText().trim();
String make = textField.getText().trim();
String model = textField_1.getText().trim();
String price = textField_3.getText().trim();
String color = textField_4.getText().trim();
String year = textField_5.getText().trim();
String sql = "UPDATE product SET inventory = inventory-1 WHERE make='" + make + "' and model = '"
+ model + "' and color ='" + color + "' and yearMade=" + year + "";
// executeUpdate for insert,delete, and update
PreparedStatement ps;
ps = Connectivity.getConnection().prepareStatement(sql);
rs = ps.executeUpdate();
String sql1 = "UPDATE employee SET commission = commission + (commissionRate*"+price+") WHERE id = "+id+"";
ps = Connectivity.getConnection().prepareStatement(sql1);
rs = ps.executeUpdate();
//inserts into sales
Random rand = new Random();
int random =rand.nextInt(999999);
String sql2 = "SELECT id FROM product WHERE make = '"+make+"' and model = '"+model+"' and color = '"+color+"' and yearMade = '"+year+"'";
st = Connectivity.getConnection().createStatement();
rs2 = st.executeQuery(sql2);
while(rs2.next()) {
int totalPrice = Integer.parseInt(price);
Double comm = totalPrice * .035;
int prodID = rs2.getInt("id");
String sql3 = "INSERT INTO sales VALUES('"+random+"','"+id+"','"+prodID+"','"+1+"','"+totalPrice+"',"+comm+")";
ps = Connectivity.getConnection().prepareStatement(sql3);
rs = ps.executeUpdate();
System.out.println(totalPrice);
System.out.println(comm);
System.out.println(ps);
}
JOptionPane.showMessageDialog(null, "Items Sold!");
}
catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnEnter.setBounds(423, 407, 130, 29);
frame5.getContentPane().add(btnEnter);
JButton button_1 = new JButton("Return to menu");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu men = new Menu();
men.frame2.setVisible(true);
frame5.setVisible(false);
}
});
button_1.setBounds(266, 407, 145, 29);
frame5.getContentPane().add(button_1);
textField_4 = new JTextField();
textField_4.setColumns(10);
textField_4.setBounds(353, 326, 185, 26);
frame5.getContentPane().add(textField_4);
JLabel label_6 = new JLabel("Year:");
label_6.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_6.setBounds(264, 374, 77, 16);
frame5.getContentPane().add(label_6);
textField_5 = new JTextField();
textField_5.setColumns(10);
textField_5.setBounds(353, 364, 185, 26);
frame5.getContentPane().add(textField_5);
JLabel lblEmployeeId = new JLabel("Employee ID:\n\n");
lblEmployeeId.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
lblEmployeeId.setBounds(245, 172, 121, 16);
frame5.getContentPane().add(lblEmployeeId);
textField_6 = new JTextField();
textField_6.setColumns(10);
textField_6.setBounds(353, 169, 185, 26);
frame5.getContentPane().add(textField_6);
JLabel imgLabel = new JLabel(new ImageIcon("/Users/jonathonmoreno/Desktop/Project/src/resize.png"));
imgLabel.setBounds(-11, 0, 845, 521);
frame5.getContentPane().add(imgLabel);
}
}

Setting a Listener to a TableModel to update as required [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am attempting to update a JTable in my GUI depending on whether a item is added or deleted. The total price in the JTextField should increment or decrement depending on the item that is removed or added. I am aware that I should use a TableModelListener to update it dynamically. I also need to set it in a total JTextField but I'm not really sure how to approach it correctly. Here is my code.
package classes;
import java.awt.*;
import java.awt.GridLayout;
import java.awt.event.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.event.*;
public class CoffeeTill_GUI extends JFrame {
private JPanel contentPane;
JLabel orderDescription = new JLabel("Order Description:");
private JTextField totalTF;
private double total = 0.0;
private double tendered = 0.0;
private double change = 0.0;
private TableModelListener tableModelListener;
// Editing An Order
//TableModelListener to listen for changes in the tableModel
private void setTableModelListener() {
tableModelListener = new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
if (e.getType() == TableModelEvent.UPDATE) {
System.out.println("Cell " + e.getFirstRow() + ", "
+ e.getColumn() + " changed. The new value: "
+ table.getModel().getValueAt(e.getFirstRow(),
e.getColumn()));
int row = e.getFirstRow();
int column = e.getColumn();
if (column == 0 || column == 1)
{
TableModel model = table.getModel();
int quantity = ((Integer) model.getValueAt(row, 0)).intValue();
double price = ((Double) model.getValueAt(row, 1)).doubleValue();
Double value = new Double(quantity * price);
model.setValueAt(value, row, 1);
}
}
}
};
table.getModel().addTableModelListener(tableModelListener);
}
// JDBC Driver name and database URL
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/team_project?useSSL=false";
final String USER_NAME = "root";
final String PASSWORD = "password";
// sql variables
Statement statement = null;
ResultSet resultSet = null;
// Update JTable when JButton is clicked
public void updateTable(int prodIn) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
Statement stmt = conn.createStatement();
String sqlString = "select ProductID, ProductName, Price from product where ProductID = " + prodIn;
stmt.executeQuery(sqlString);
} catch (Exception e) {
e.printStackTrace();
}
}
// creating new stock item
Stock productPrice = new Stock();
Stock productName = new Stock();
JTable table = new JTable();
JButton delButton = new JButton("DEL");
JButton minusButton = new JButton("-");
JButton plusButton = new JButton("+");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CoffeeTill_GUI frame = new CoffeeTill_GUI();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
// Connection Object
Connection connection = null;
private JTextField tenderedTF;
private JTextField changeTF;
/**
* Create the frame.
*/
public CoffeeTill_GUI() {
try {
connection = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1200, 686);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
// COFFEE PANEL - START -----------------------------------------
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(20, 74, 796, 563);
contentPane.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("Coffee", null, panel, null);
panel.setLayout(null);
JLabel lblCoffee = new JLabel("Americano");
lblCoffee.setHorizontalAlignment(SwingConstants.CENTER);
lblCoffee.setFont(new Font("Tahoma", Font.PLAIN, 30));
lblCoffee.setBounds(10, 45, 154, 45);
panel.add(lblCoffee);
JLabel label = new JLabel("Cappucino");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("Tahoma", Font.PLAIN, 30));
label.setBounds(10, 117, 154, 45);
panel.add(label);
JLabel label_1 = new JLabel("Espresso");
label_1.setHorizontalAlignment(SwingConstants.CENTER);
label_1.setFont(new Font("Tahoma", Font.PLAIN, 30));
label_1.setBounds(10, 191, 154, 45);
panel.add(label_1);
JLabel label_2 = new JLabel("Latte");
label_2.setHorizontalAlignment(SwingConstants.CENTER);
label_2.setFont(new Font("Tahoma", Font.PLAIN, 30));
label_2.setBounds(10, 274, 154, 45);
panel.add(label_2);
JLabel label_3 = new JLabel("Mocha");
label_3.setHorizontalAlignment(SwingConstants.CENTER);
label_3.setFont(new Font("Tahoma", Font.PLAIN, 30));
label_3.setBounds(10, 355, 154, 45);
panel.add(label_3);
JLabel label_4 = new JLabel("Macchiato");
label_4.setHorizontalAlignment(SwingConstants.CENTER);
label_4.setFont(new Font("Tahoma", Font.PLAIN, 30));
label_4.setBounds(10, 440, 154, 45);
panel.add(label_4);
JButton americanoSmall = new JButton("SMALL");
americanoSmall.setBounds(191, 45, 164, 45);
panel.add(americanoSmall);
JButton americanoMedium = new JButton("MEDIUM");
americanoMedium.setBounds(365, 45, 164, 45);
panel.add(americanoMedium);
JButton americanoLarge = new JButton("LARGE");
americanoLarge.setBounds(539, 45, 164, 45);
panel.add(americanoLarge);
JButton cappuchinoSmall = new JButton("SMALL");
cappuchinoSmall.setBounds(191, 117, 164, 45);
panel.add(cappuchinoSmall);
JButton cappuchinoMedium = new JButton("MEDIUM");
cappuchinoMedium.setBounds(365, 117, 164, 45);
panel.add(cappuchinoMedium);
JButton cappuchinoLarge = new JButton("LARGE");
cappuchinoLarge.setBounds(539, 117, 164, 45);
panel.add(cappuchinoLarge);
JButton espressoSmall = new JButton("SMALL");
espressoSmall.setBounds(191, 191, 164, 45);
panel.add(espressoSmall);
JButton espressoMedium = new JButton("MEDIUM");
espressoMedium.setBounds(365, 191, 164, 45);
panel.add(espressoMedium);
JButton espressoLarge = new JButton("LARGE");
espressoLarge.setBounds(539, 191, 164, 45);
panel.add(espressoLarge);
JButton latteSmall = new JButton("SMALL");
latteSmall.setBounds(191, 274, 164, 45);
panel.add(latteSmall);
JButton latteMedium = new JButton("MEDIUM");
latteMedium.setBounds(365, 274, 164, 45);
panel.add(latteMedium);
JButton latteLarge = new JButton("LARGE");
latteLarge.setBounds(539, 274, 164, 45);
panel.add(latteLarge);
JButton mochaSmall = new JButton("SMALL");
mochaSmall.setBounds(191, 355, 164, 45);
panel.add(mochaSmall);
JButton mochaMedium = new JButton("MEDIUM");
mochaMedium.setBounds(365, 355, 164, 45);
panel.add(mochaMedium);
JButton mochaLarge = new JButton("LARGE");
mochaLarge.setBounds(539, 355, 164, 45);
panel.add(mochaLarge);
JButton macchiatoSmall = new JButton("SMALL");
macchiatoSmall.setBounds(191, 440, 164, 45);
panel.add(macchiatoSmall);
JButton macchiatoMedium = new JButton("MEDIUM");
macchiatoMedium.setBounds(365, 440, 164, 45);
panel.add(macchiatoMedium);
JButton macchiatoLarge = new JButton("LARGE");
macchiatoLarge.setBounds(539, 440, 164, 45);
panel.add(macchiatoLarge);
// COFFEE PANEL - END -----------------------------------------
// COLD DRINKS PANELS - START -----------------------------------------
JPanel panel_1 = new JPanel();
tabbedPane.addTab("Cold Drinks", null, panel_1, null);
panel_1.setLayout(new GridLayout(2, 2));
ImageIcon waterIcon, cokeIcon, spriteIcon, fantaIcon;
JButton waterButton, cokeButton, spriteButton, fantaButton;
panel_1.add(waterButton = new JButton(waterIcon = new ImageIcon("image/water.jpg")));
panel_1.add(cokeButton = new JButton(cokeIcon = new ImageIcon("image/coke.jpg")));
panel_1.add(spriteButton = new JButton(spriteIcon = new ImageIcon("image/sprite.jpg")));
panel_1.add(fantaButton = new JButton(fantaIcon = new ImageIcon("image/fanta.jpg")));
// COLD DRINKS PANEL - END -----------------------------------------
// SANDWICHES - START -----------------------------------------
JButton hamAndCheese, bltButton, tunaAndSweetcorn, chickenAndHam, hamAndCheesePanini;
JPanel panel_2 = new JPanel();
tabbedPane.addTab("Sandwiches", null, panel_2, null);
panel_2.setLayout(new GridLayout(5, 1));
panel_2.add(hamAndCheese = new JButton("Ham & Cheese"));
panel_2.add(bltButton = new JButton("BLT"));
panel_2.add(tunaAndSweetcorn = new JButton("Tuna & Sweetcorn"));
panel_2.add(chickenAndHam = new JButton("Chicken & Ham"));
panel_2.add(hamAndCheesePanini = new JButton("Ham & Cheese Panini"));
// SANDWICHES - END -----------------------------------------
// PASTRIES - START -----------------------------------------
JButton danishPastryJbt, muffinJbt, cinnamonRoleJbt, profiteroleJbt, eclairJbt, croissantJbt;
JPanel panel_3 = new JPanel();
panel_3.setLayout(new GridLayout(6, 1));
tabbedPane.addTab("Pastries", null, panel_3, null);
panel_3.add(danishPastryJbt = new JButton("Danish Pastry"));
panel_3.add(muffinJbt = new JButton("Muffin"));
panel_3.add(cinnamonRoleJbt = new JButton("Cinnamon Role"));
panel_3.add(profiteroleJbt = new JButton("Profiterole"));
panel_3.add(eclairJbt = new JButton("Eclair"));
panel_3.add(croissantJbt = new JButton("Croissant"));
orderDescription.setFont(new Font("Tahoma", Font.PLAIN, 20));
orderDescription.setBounds(845, 55, 214, 33);
contentPane.add(orderDescription);
// ORDER - END -----------------------------------------
// HEADING - START -----------------------------------------
JLabel lblUserEmployee = new JLabel("User: Employee1");
lblUserEmployee.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblUserEmployee.setBounds(20, 11, 204, 33);
contentPane.add(lblUserEmployee);
JLabel lblJavaHouseCoffee = new JLabel("Java House Coffee");
lblJavaHouseCoffee.setHorizontalAlignment(SwingConstants.CENTER);
lblJavaHouseCoffee.setFont(new Font("Tahoma", Font.PLAIN, 40));
lblJavaHouseCoffee.setBounds(333, 11, 480, 60);
contentPane.add(lblJavaHouseCoffee);
// Setting the Time on the GUI
JLabel lblTime = new JLabel("");
String timeStamp = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss").format(Calendar.getInstance().getTime());
lblTime.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblTime.setBounds(650, 0, 120, 30);
lblTime.setText(timeStamp + "");
lblTime.setVisible(true);
int delay = 1000; // milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String date = new java.text.SimpleDateFormat("HH:mm:ss")
.format(new java.util.Date(System.currentTimeMillis()));
lblTime.setText("" + Calendar.getInstance().getTime());
}
};
new Timer(delay, taskPerformer).start();
lblTime.setHorizontalAlignment(SwingConstants.CENTER);
lblTime.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblTime.setBounds(914, 11, 244, 45);
contentPane.add(lblTime);
// add header of the table
String columns[] = new String[] { "Product Name", "Price" };
DefaultTableModel dtm = new DefaultTableModel(columns, 0);
dtm.setColumnIdentifiers(columns);
table.setModel(dtm);
// round the prices values pulled from DB to 2 Decimal Places
table.getColumnModel().getColumn(1).setCellRenderer(new DecimalFormatRenderer());
getContentPane().add(new JScrollPane(table));
table.setFont(new Font("Serif", Font.PLAIN, 18));
// add header of the table
JScrollPane scrollPaneTable = new JScrollPane(table);
scrollPaneTable.setBounds(845, 94, 329, 241);
contentPane.add(scrollPaneTable);
JPanel panel_5 = new JPanel();
scrollPaneTable.setColumnHeaderView(panel_5);
panel_5.setLayout(new BorderLayout());
JLabel totalJLabel = new JLabel("Total €");
totalJLabel.setFont(new Font("Tahoma", Font.PLAIN, 20));
totalJLabel.setBounds(899, 400, 63, 45);
contentPane.add(totalJLabel);
totalTF = new JTextField();
totalTF.setFont(new Font("Tahoma", Font.PLAIN, 20));
totalTF.setBounds(970, 400, 204, 45);
contentPane.add(totalTF);
totalTF.setColumns(10);
totalTF.setEditable(false);
delButton.setBounds(845, 346, 96, 45);
contentPane.add(delButton);
delButton.setFont(new Font("Tahoma", Font.PLAIN, 15));
minusButton.setBounds(963, 346, 96, 45);
contentPane.add(minusButton);
minusButton.setFont(new Font("Tahoma", Font.PLAIN, 15));
plusButton.setBounds(1083, 346, 87, 45);
contentPane.add(plusButton);
plusButton.setFont(new Font("Tahoma", Font.PLAIN, 15));
JLabel tenderedJLabel = new JLabel("Tendered €");
tenderedJLabel.setFont(new Font("Tahoma", Font.PLAIN, 20));
tenderedJLabel.setBounds(858, 456, 102, 45);
contentPane.add(tenderedJLabel);
tenderedTF = new JTextField();
tenderedTF.setFont(new Font("Tahoma", Font.PLAIN, 20));
tenderedTF.setBounds(972, 456, 202, 45);
contentPane.add(tenderedTF);
tenderedTF.setColumns(10);
JLabel changeJlabel = new JLabel("Change €");
changeJlabel.setFont(new Font("Tahoma", Font.PLAIN, 20));
changeJlabel.setBounds(878, 521, 84, 37);
contentPane.add(changeJlabel);
changeTF = new JTextField();
changeTF.setFont(new Font("Tahoma", Font.PLAIN, 20));
changeTF.setEditable(false);
changeTF.setBounds(972, 512, 202, 46);
contentPane.add(changeTF);
changeTF.setColumns(10);
// Delete row from JTable when clicked by user
delButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int viewIndex = table.getSelectedRow();
if (viewIndex != -1) {
// converts the row index in the view to the appropriate
// index in the model
int modelIndex = table.convertRowIndexToModel(viewIndex);
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.removeRow(modelIndex);
}
}
});
table.getTableHeader().setReorderingAllowed(false);
// HEADING - END -----------------------------------------
// Small Americano ActionListener
americanoSmall.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "select ProductName, Price from product where ProductID = 24";
java.sql.PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
// Loop through the ResultSet and transfer in the Model
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
while (rs.next()) {
Object[] objects = new Object[colNo];
for (int i = 0; i < colNo; i++) {
objects[i] = rs.getObject(i + 1);
}
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(objects);
Stock s = new Stock();
// deduct stock from db from
// s1.deductStock(24);
total = total + s.getItemPrice(24);
totalTF.setText(String.valueOf(total));
totalTF.setText(String.format("%.2f", total));
}
TableModel model = (DefaultTableModel) table.getModel();
table.setModel(model);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
americanoMedium.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "select ProductName, Price from product where ProductID = 25";
java.sql.PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
// Loop through the ResultSet and transfer in the Model
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
while (rs.next()) {
Object[] objects = new Object[colNo];
for (int i = 0; i < colNo; i++) {
objects[i] = rs.getObject(i + 1);
}
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(objects);
Stock s = new Stock();
// deduct stock from db from
// s1.deductStock(24);
total = total + s.getItemPrice(25);
totalTF.setText(String.valueOf(total));
totalTF.setText(String.format("%.2f", total));
}
TableModel model = (DefaultTableModel) table.getModel();
table.setModel(model);
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
americanoLarge.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "select ProductName, Price from product where ProductID = 26";
java.sql.PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
// Loop through the ResultSet and transfer in the Model
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
while (rs.next()) {
Object[] objects = new Object[colNo];
for (int i = 0; i < colNo; i++) {
objects[i] = rs.getObject(i + 1);
}
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(objects);
Stock s = new Stock();
// deduct stock from db from
// s1.deductStock(24);
total = total + s.getItemPrice(26);
totalTF.setText(String.valueOf(total));
totalTF.setText(String.format("%.2f", total));
}
TableModel model = (DefaultTableModel) table.getModel();
table.setModel(model);
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
cappuchinoSmall.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "select ProductName, Price from product where ProductID = 30";
java.sql.PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
// Loop through the ResultSet and transfer in the Model
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
while (rs.next()) {
Object[] objects = new Object[colNo];
for (int i = 0; i < colNo; i++) {
objects[i] = rs.getObject(i + 1);
}
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(objects);
Stock s = new Stock();
// deduct stock from db from
// s1.deductStock(24);
total = total + s.getItemPrice(30);
totalTF.setText(String.valueOf(total));
totalTF.setText(String.format("%.2f", total));
}
TableModel model = (DefaultTableModel) table.getModel();
table.setModel(model);
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
cappuchinoMedium.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "select ProductName, Price from product where ProductID = 31";
java.sql.PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
// Loop through the ResultSet and transfer in the Model
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
while (rs.next()) {
Object[] objects = new Object[colNo];
for (int i = 0; i < colNo; i++) {
objects[i] = rs.getObject(i + 1);
}
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(objects);
Stock s = new Stock();
// deduct stock from db from
// s1.deductStock(24);
total = total + s.getItemPrice(31);
totalTF.setText(String.valueOf(total));
totalTF.setText(String.format("%.2f", total));
}
TableModel model = (DefaultTableModel) table.getModel();
table.setModel(model);
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
cappuchinoLarge.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "select ProductName, Price from product where ProductID = 32";
java.sql.PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
// Loop through the ResultSet and transfer in the Model
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
while (rs.next()) {
Object[] objects = new Object[colNo];
for (int i = 0; i < colNo; i++) {
objects[i] = rs.getObject(i + 1);
}
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(objects);
Stock s = new Stock();
// deduct stock from db from
// s1.deductStock(24);
total = total + s.getItemPrice(32);
totalTF.setText(String.valueOf(total));
totalTF.setText(String.format("%.2f", total));
}
TableModel model = (DefaultTableModel) table.getModel();
table.setModel(model);
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
JButton payButton = new JButton("Pay");
payButton.setBounds(970, 569, 209, 51);
contentPane.add(payButton);;
}// end class
So this is very basic proof of concept.
What this does is, it maintains an internal "proxy"/"cache" of the values which are added/removed/updated. In this way, it's capable of using the event information to simply update the tally without having to re-iterate the model, which can be time consuming.
When you create a new model, you should attach the the listener to it, BEFORE populating it, this will give the listener the opportunity to be notified of new rows and update its internal state.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private DefaultTableModel model;
private JTextField tallyField;
private double tally;
public TestPane() {
setLayout(new BorderLayout());
tallyField = new JTextField(10);
// When loading data, update this value to represent the total
// of the data that was loaded
tally = 0;
model = new DefaultTableModel(new Object[]{"Quanity", "Amount"}, 0);
model.addTableModelListener(new TableModelListener() {
private Map<Integer, Double> proxy = new HashMap<Integer, Double>();
private NumberFormat nf = NumberFormat.getCurrencyInstance();
#Override
public void tableChanged(TableModelEvent e) {
int firstRow = e.getFirstRow();
int lastRow = e.getLastRow();
double sum = 0;
for (int row = Math.min(firstRow, lastRow); row <= Math.max(firstRow, lastRow); row++) {
switch (e.getType()) {
case TableModelEvent.DELETE:
sum -= delete(row);
break;
case TableModelEvent.INSERT:
sum += add(row);
break;
case TableModelEvent.UPDATE:
sum -= delete(row);
sum += add(row);
break;
default:
break;
}
}
tally += sum;
tallyField.setText(nf.format(tally));
}
protected double delete(int row) {
double sum = 0;
if (proxy.containsKey(row)) {
sum = proxy.get(row);
}
proxy.remove(row);
return sum;
}
protected double add(int row) {
int qty = 0;
// I hope your model is better setup then mine
if (model.getValueAt(row, 0) instanceof String) {
qty = Integer.parseInt((String) model.getValueAt(row, 0));
} else if (model.getValueAt(row, 0) instanceof Integer) {
qty = (Integer) model.getValueAt(row, 0);
}
double amount = (Double) model.getValueAt(row, 1);
double rowTotal = qty * amount;
proxy.put(row, rowTotal);
return rowTotal;
}
});
JTable table = new JTable(model);
add(new JScrollPane(table));
JButton add = new JButton("Add");
JButton delete = new JButton("Delete");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
double amount = 1.0; //Math.random() * 1000.0;
model.addRow(new Object[]{1, amount});
}
});
delete.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int[] rows = table.getSelectedRows();
List<Integer> selection = new ArrayList<>(rows.length);
for (int row : rows) {
selection.add(row);
}
Collections.sort(selection);
Collections.reverse(selection);
for (int row : selection) {
model.removeRow(row);
}
}
});
JPanel footer = new JPanel(new BorderLayout());
JPanel buttons = new JPanel();
buttons.add(add);
buttons.add(delete);
footer.add(tallyField);
footer.add(buttons, BorderLayout.SOUTH);
add(footer, BorderLayout.SOUTH);
}
}
}
Why do we need the cache? Because when a row is deleted, you can no longer determine it's value.
If I was doing this in a real application, I would make a simple class that implements TableModelListener but which provided a getter to retrieve the tally (so the tally becomes encapsulated to the class) and use an observer pattern to generate notifications when the tally is changed.
This means that when you load the data, you can update the model and "tally monitor" independently. And when you need to, update the required fields on the screen.
This can become very complicated, very quickly. I did something simular to produce a automatic tallying system for tallying rows and columns independently of the model, so the system wasn't coupled to the model structure apart from known which row/column it was responsible for tallying

How to make JFrame login form work?

I am doing a project on library management in java using swing on eclipse. When I click on the login button nothing happens. The mysql jdbc driver is loaded and I am getting the connection but no label appears. Please tell me what to do. Here is my code.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class Loginscreen implements ActionListener {
JFrame logframe;
JButton bt;
JLabel lid, lpass, lmsg;
JTextField tid;
JPasswordField pass;
JPanel p1;
Font ft, ft2;
Connection conn;
public Loginscreen() {
logframe = new JFrame("Login");
logframe.setSize(1366, 720);
logframe.setVisible(true);
lid = new JLabel("User ID");
lpass = new JLabel("Password");
lmsg = new JLabel();
ft = new Font("Arial", Font.BOLD, 30);
ft2 = new Font("Arial", Font.PLAIN, 20);
tid = new JTextField();
pass = new JPasswordField();
p1 = new JPanel();
bt = new JButton("Login");
logframe.add(p1);
p1.setLayout(null);
p1.setBackground(new Color(160, 82, 45));//Background Color Set
lid.setBounds(450, 200, 500, 30);
p1.add(lid);
lid.setFont(ft);
tid.setBounds(650, 200, 200, 30);
p1.add(tid);
tid.setFont(ft2);
lpass.setBounds(450, 300, 500, 30);
p1.add(lpass);
lpass.setFont(ft);
pass.setBounds(650, 300, 200, 30);
p1.add(pass);
bt.setBounds(600, 430, 100, 50);
p1.add(bt);
bt.setFont(new Font("Segoe Script", Font.BOLD, 22));
bt.setBackground(new Color(173, 216, 230));
lmsg.setBounds(450, 510, 500, 30);
p1.add(lmsg);
bt.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == bt) {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_lib", "root", "admin");
String i = tid.getText();//get the user id
char[] pwd = pass.getPassword();//get the password
String spwd = new String(pwd);//converting char to string
String query = "select * from tbl_user where id=? and password=?";
PreparedStatement p = conn.prepareStatement(query);
p.setString(1, i);
p.setString(2, spwd);
ResultSet rs = p.executeQuery();
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
lmsg.setText("Invalid User ID or Password");
} else {
lmsg.setText("Invalid User ID or Password");
}
rs.close();
conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
I guess you dont set the text when it succeeds.
Also make sure
while(rs.next())
{
count=count+1;
}
terminates.
Also secure your query against SQL-Injection (just realized this)
For these kinds of debugging problems I recommend UnitTesting (basically just test how far the program goes, how long it takes, if it terminates etc).
Also before you post a question, do us a favor to add comments and format the GUI-stuff properly...it looks horrible :/
EDIT:
if(count==1)
{
lmsg.setText("Invalid User ID or Password");
}
else
{
lmsg.setText("Invalid User ID or Password");
}
Does not make sense to me... Whatever happens you return an error

Why the prepared statement not working in java?

I am trying to get the student information by providing the roll number and medium from db. The swing application executed without any error but when I enter the roll no and medium then its going to the "Student not Found" else loop.
I guess the problems with get string or the prepared statements.kindly help me to find out the issue.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
public class Searchdb extends JFrame implements ActionListener {
//Initializing Components
JLabel lb,lbd,lb1, lb2, lb3, lb5;
JTextField tf1, tf2,tf3,tf5,tfd;
JButton btn;
//Creating Constructor for initializing JFrame components
Searchdb() {
//Providing Title
super("Fetching Roll Information");
lb5 = new JLabel("Roll Number:");
lb5.setBounds(20, 20, 100, 20);
tf5 = new JTextField(20);
tf5.setBounds(130, 20, 200, 20);
lbd = new JLabel("Date:");
lbd.setBounds(20, 50, 100, 20);
tfd = new JTextField(20);
tfd.setBounds(130, 50, 200, 20);
btn = new JButton("Submit");
btn.setBounds(50, 50, 100, 20);
btn.addActionListener(this);
lb = new JLabel("Fetching Student Information From Database");
lb.setBounds(30, 80, 450, 30);
lb.setForeground(Color.black);
lb.setFont(new Font("Serif", Font.PLAIN, 12));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
lb1 = new JLabel("Name:");
lb1.setBounds(20, 120, 100, 20);
tf1 = new JTextField(50);
tf1.setBounds(130, 120, 200, 20);
lb2 = new JLabel("Fathername:");
lb2.setBounds(20, 150, 100, 20);
tf2 = new JTextField(100);
tf2.setBounds(130, 150, 200, 20);
lb3 = new JLabel("State:");
lb3.setBounds(20, 180, 100, 20);
tf3 = new JTextField(50);
tf3.setBounds(130, 180, 200, 20);
setLayout(null);
//Add components to the JFrame
add(lb5);
add(tf5);
add(lbd);
add(tfd);
add(btn);
add(lb);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
//Set TextField Editable False
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
}
public void actionPerformed(ActionEvent e) {
//Create DataBase Coonection and Fetching Records
try {
String str = tf5.getText();
Datestri = tfd.getText();//Getting the unable to convert String to Date error
System.out.println(str);
System.out.println(stri);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#//host:port/servicename","username","password");
PreparedStatement st = con.prepareStatement("select Name,Fathername,State from student_db where roll_number=? and medium=?");
System.out.println(st);
st.setString(1, str);
st.setDate(2, stri);
//Excuting Query
ResultSet rs = st.executeQuery();
System.out.println(rs);
if (rs.next()) {
String s = rs.getString(1);
String s1 = rs.getString(2);
String s2 = rs.getString(3);
//Sets Records in TextFields.
tf1.setText(s);
tf2.setText(s1);
tf3.setText(s2);
} else {
JOptionPane.showMessageDialog(null, "Student not Found");
}
//Create Exception Handler
} catch (Exception ex) {
System.out.println(ex);
}
}
//Running Constructor
public static void main(String args[]) {
new Searchdb();
}
}
sql query:
select Name,Fathername,State from student_db where roll_number='1441' and medium='2016-12-18';
Results:
Name Fathername State
SA TH YA
Suppose if i am not passing the "Stri" variable in the query i am getting the results.
I have updated the code below and its working fine, when i checked the database type for the medium column name it is varchar2(40), so i decided to use the getString only.
Getting proper response with this code,
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
public class Searchdb extends JFrame implements ActionListener {
//Initializing Components
JLabel lb,lbd,lb1, lb2, lb3, lb5;
JTextField tf1, tf2,tf3,tf5,tfd;
JButton btn;
//Creating Constructor for initializing JFrame components
Searchdb() {
//Providing Title
super("Fetching Roll Information");
lb5 = new JLabel("Roll Number:");
lb5.setBounds(20, 20, 100, 20);
tf5 = new JTextField(20);
tf5.setBounds(130, 20, 200, 20);
lbd = new JLabel("Date:");
lbd.setBounds(20, 50, 100, 20);
tfd = new JTextField(20);
tfd.setBounds(130, 50, 200, 20);
btn = new JButton("Submit");
btn.setBounds(50, 50, 100, 20);
btn.addActionListener(this);
lb = new JLabel("Fetching Student Information From Database");
lb.setBounds(30, 80, 450, 30);
lb.setForeground(Color.black);
lb.setFont(new Font("Serif", Font.PLAIN, 12));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
lb1 = new JLabel("Name:");
lb1.setBounds(20, 120, 100, 20);
tf1 = new JTextField(50);
tf1.setBounds(130, 120, 200, 20);
lb2 = new JLabel("Fathername:");
lb2.setBounds(20, 150, 100, 20);
tf2 = new JTextField(100);
tf2.setBounds(130, 150, 200, 20);
lb3 = new JLabel("State:");
lb3.setBounds(20, 180, 100, 20);
tf3 = new JTextField(50);
tf3.setBounds(130, 180, 200, 20);
setLayout(null);
//Add components to the JFrame
add(lb5);
add(tf5);
add(lbd);
add(tfd);
add(btn);
add(lb);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
//Set TextField Editable False
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
}
public void actionPerformed(ActionEvent e) {
//Create DataBase Coonection and Fetching Records
try {
String str = tf5.getText();
String stri = tfd.getText();
System.out.println(str);
System.out.println(stri);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#//host:port/servicename","username","password");
String str1 ="select Name,Fathername,State from student_db where roll_number='"+str+"' and medium='"+stri+"'";
PreparedStatement st = con.prepareStatement(str1);
System.out.println(st);
st.setString(1, str);
st.setString(2, stri);
//Excuting Query
ResultSet rs = st.executeQuery();
System.out.println(rs);
if (rs.next()) {
String s = rs.getString(1);
String s1 = rs.getString(2);
String s2 = rs.getString(3);
//Sets Records in TextFields.
tf1.setText(s);
tf2.setText(s1);
tf3.setText(s2);
} else {
JOptionPane.showMessageDialog(null, "Student not Found");
}
//Create Exception Handler
} catch (Exception ex) {
System.out.println(ex);
}
}
//Running Constructor
public static void main(String args[]) {
new Searchdb();
}
}

java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 2

This is my javax.swing class. But it always throws the error java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 2. Not quite sure what is causing it. Where is the error?
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import javax.swing.*;
public class SwingSearchApp extends JFrame implements ActionListener {
//Initializing Components
private static final long serialVersionUID = 1L;
JLabel lb, lb1, lb2, lb3, lb4, lb5;
JTextField tf1, tf2, tf3, tf4, tf5;
JButton btn;
//Creating Constructor for initializing JFrame components
SwingSearchApp() {
//Providing Title
super("Fetching Student Information");
lb5 = new JLabel("Enter Name:");
lb5.setBounds(20, 20, 100, 20);
tf5 = new JTextField(20);
tf5.setBounds(130, 20, 200, 20);
btn = new JButton("Submit");
btn.setBounds(50, 50, 100, 20);
btn.addActionListener(this);
lb = new JLabel("Fetching Search Information From Database");
lb.setBounds(30, 80, 450, 30);
lb.setForeground(Color.red);
lb.setFont(new Font("Serif", Font.BOLD, 20));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
lb1 = new JLabel("U_Name:");
lb1.setBounds(20, 120, 100, 20);
tf1 = new JTextField(50);
tf1.setBounds(130, 120, 200, 20);
lb2 = new JLabel("U_Mail:");
lb2.setBounds(20, 150, 100, 20);
tf2 = new JTextField(100);
tf2.setBounds(130, 150, 200, 20);
lb3 = new JLabel("U_Pass:");
lb3.setBounds(20, 180, 100, 20);
tf3 = new JTextField(50);
tf3.setBounds(130, 180, 200, 20);
lb4 = new JLabel("U_Country:");
lb4.setBounds(20, 210, 100, 20);
tf4 = new JTextField(50);
tf4.setBounds(130, 210, 100, 20);
setLayout(null);
//Add components to the JFrame
add(lb5);
add(tf5);
add(btn);
add(lb);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
add(lb4);
add(tf4);
//Set TextField Editable False
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
tf4.setEditable(false);
}
public void actionPerformed(ActionEvent e) {
//Create DataBase Coonection and Fetching Records
try {
String str = tf5.getText();
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\employee.accdb";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, "", "");
//Connection con = DriverManager.getConnection("jdbc:oracle:thin:#mcndesktop07:1521", "sandeep", "welcome");
PreparedStatement st = con.prepareStatement("select * from emp where uname=?");
st.setString(1, str);
//Excuting Query
ResultSet rs = st.executeQuery();
if (rs.next()) {
String s = rs.getString(1);
String s1 = rs.getString(2);
String s2 = rs.getString(3);
String s3 = rs.getString(4);
//Sets Records in TextFields.
tf1.setText(s);
tf2.setText(s1);
tf3.setText(s2);
tf4.setText(s3);
} else {
JOptionPane.showMessageDialog(null, "Name not Found");
}
//Create Exception Handler
} catch (Exception ex) {
System.out.println(ex);
}
}
//Running Constructor
public static void main(String args[]) {
new SwingSearchApp();
}
}
The structure of my table in Access database contains the following fields:-
uname, umail, upass, upcountry.
This can happen if uname doesn't exist in your table. Check the spelling/case.
Reference: here
Update:
Try to modify your code a little to be able to just run a simple query and get a result set. This will then allow you to query for the column names as your driver sees them:
ResultSet rs = stmt.executeQuery("SELECT * FROM emp");
ResultSetMetaData rsmd = rs.getMetaData();
String firstColumnName = rsmd.getColumnName(1);
// etc..
That will tell you for sure.

Categories

Resources