Why the prepared statement not working in java? - 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();
}
}

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);
}
}

Jcombobox not selecting item

Im trying to insert the Jcombobox value into my sqlite database but whenever I run the program, it only inserts '9' in to my database. Please advise. I am trying to import the integer that the user picks into my sqlite database. For some reason, even with the action listener, the default value, 9, is still being inputed into the table and im not sure why. Here is the full code, not including the connection and the Jtable.
public class create extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
create frame = new create();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connect = null;
private JTextField textField_2;
String uniqueString = UUID.randomUUID().toString();
private JTextField textField_3;
/**
* Create the frame.
*/
public create() {
connect = connection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBackground(new Color(204, 204, 204));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblStudentName = new JLabel("Student ID:");
lblStudentName.setBounds(96, 69, 72, 16);
contentPane.add(lblStudentName);
textField = new JTextField();
textField.setBounds(173, 64, 216, 26);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblGrade = new JLabel("Grade:");
lblGrade.setBounds(125, 107, 47, 16);
contentPane.add(lblGrade);
JComboBox comboBox = new JComboBox();
comboBox.addItem(9);
comboBox.addItem(10);
comboBox.addItem(11);
comboBox.addItem(12);
comboBox.setBounds(173, 102, 72, 29);
contentPane.add(comboBox);
comboBox.setSelectedItem(9);
comboBox.addActionListener(comboBox);
int selectedNumber = (int)comboBox.getSelectedItem();
JLabel lblInputBookOver = new JLabel("Teacher:");
lblInputBookOver.setBounds(111, 146, 61, 21);
contentPane.add(lblInputBookOver);
textField_1 = new JTextField();
textField_1.setBounds(173, 143, 216, 26);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton button = new JButton("<");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int count = 0; count <= 0; count++) {
//dispose();
options sc = new options();
sc.setVisible(true);
}
}
});
button.setBounds(6, 6, 30, 29);
contentPane.add(button);
JLabel lblStudentname = new JLabel("Student Name:");
lblStudentname.setBounds(74, 31, 99, 16);
contentPane.add(lblStudentname);
textField_2 = new JTextField();
textField_2.setBounds(173, 26, 216, 26);
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(125, 180, 42, 26);
contentPane.add(lblEmail);
textField_3 = new JTextField();
textField_3.setBounds(173, 180, 216, 26);
contentPane.add(textField_3);
textField_3.setColumns(10);
JButton btnCheckout = new JButton("Checkout");
btnCheckout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String uniqueString = UUID.randomUUID().toString().replace("-", "");
try {
String query = "insert into data ('Name', 'Student ID', 'Teacher', 'Grade', 'Email', 'Ebook') values (?,?,?,?,?,?)";
PreparedStatement pst = connect.prepareStatement(query);
pst.setString(1,textField_2.getText() );
pst.setString(2,textField.getText() );
pst.setString(3,textField_1.getText() );
pst.setInt(4, selectedNumber);
pst.setString(5,textField_3.getText() );
pst.setString(6, uniqueString);
for (int count = 0; count <= 0; count++) {
//dispose();
confirm sc = new confirm();
sc.setVisible(true);
count = 0;
}
pst.execute();
pst.close();
}
catch (Exception w){
w.printStackTrace();
}
}
});
btnCheckout.setBounds(173, 218, 117, 29);
contentPane.add(btnCheckout);
}
}
It inserts 9 to your database because the selected item is always 9, and this because you add it first to your combobox. In order to insert the selected value, you will have to use an ActionListener. Then you can take user's selection and do whatever you want.
An example of its usage:
import java.awt.FlowLayout;
import java.io.FileNotFoundException;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class ComboBox extends JFrame {
public ComboBox() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
getContentPane().setLayout(new FlowLayout());
Integer[] numbers = { 4, 5, 8, 123, 42, 634 };
JComboBox<Integer> comboBox = new JComboBox<>(numbers);
comboBox.setSelectedItem(42); // The initial selection is 42.
comboBox.addActionListener(e -> {
int selectedNumber = (int) comboBox.getSelectedItem();
System.out.println("Selected number: " + selectedNumber);
// Do whatever with selected number
});
add(comboBox);
}
public static void main(String[] args) throws FileNotFoundException {
SwingUtilities.invokeLater(() -> new ComboBox().setVisible(true));
}
}

How to update row selected by id column?

This a 'form'with textfields where admin can update
//For Update
public AdminCreateQnsPanel(JFrame mf, QuizDetails q, int set, String topic) {
super(mf);
System.out.println("**** admin create qns panel *"+ q.getQuestionNo());
System.out.println("**** admin create qns panel *"+ q.getQuestionDesc());
System.out.println("**** admin create qns panel *"+ q.getOption1());
System.out.println("**** admin create qns panel *"+ q.getOption2());
JLabel lblSet = new JLabel("Set 1");
lblSet.setFont(new Font("Tahoma", Font.BOLD, 30));
lblSet.setBounds(29, 160, 141, 28) ;
add(lblSet);
JLabel lblQnsDesc = new JLabel("Question Description :");
lblQnsDesc.setFont(new Font("Tahoma", Font.BOLD, 16));
lblQnsDesc.setBounds(76, 270, 181, 20);
add(lblQnsDesc);
txtfQnsDesc = new JTextField();
txtfQnsDesc.setColumns(10);
txtfQnsDesc.setBounds(76, 306, 639, 26);
add(txtfQnsDesc);
txtfQnsDesc.setText(q.getQuestionDesc());
JLabel lblOp1 = new JLabel("Option 1 :");
lblOp1.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp1.setBounds(76, 365, 103, 20);
add(lblOp1);
txtfOp1 = new JTextField();
txtfOp1.setColumns(10);
txtfOp1.setBounds(218, 362, 146, 26);
add(txtfOp1);
txtfOp1.setText(q.getOption1());
JLabel lblOp2 = new JLabel("Option 2 :");
lblOp2.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp2.setBounds(76, 418, 103, 20);
add(lblOp2);
txtfOp2 = new JTextField();
txtfOp2.setColumns(10);
txtfOp2.setBounds(218, 415, 146, 26);
add(txtfOp2);
txtfOp2.setText(q.getOption2());
JLabel lblOp3 = new JLabel("Option 3 :");
lblOp3.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp3.setBounds(76, 468, 103, 20);
add(lblOp3);
txtfOp3 = new JTextField();
txtfOp3.setColumns(10);
txtfOp3.setBounds(218, 465, 146, 26);
add(txtfOp3);
txtfOp3.setText(q.getOption3());
JLabel lblOp4 = new JLabel("Option 4 :");
lblOp4.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp4.setBounds(76, 515, 103, 20);
add(lblOp4);
txtfOp4 = new JTextField();
txtfOp4.setColumns(10);
txtfOp4.setBounds(218, 512, 146, 26);
add(txtfOp4);
txtfOp4.setText(q.getOption4());
JLabel lblCorrAns = new JLabel("Correct Answer :");
lblCorrAns.setFont(new Font("Tahoma", Font.BOLD, 16));
lblCorrAns.setBounds(76, 581, 151, 20);
add(lblCorrAns);
txtfCorrAns = new JTextField();
txtfCorrAns.setColumns(10);
txtfCorrAns.setBounds(218, 578, 146, 26);
add(txtfCorrAns);
txtfCorrAns.setText(q.getCorrectAnswer());
JButton button = new JButton("Add");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedAdd();
//actionPerformedOk();
}
});
button.setFont(new Font("Tahoma", Font.BOLD, 16));
button.setBounds(428, 622, 115, 29);
add(button);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminQuizOverallPanel(myFrame, set, topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnCancel.setFont(new Font("Tahoma", Font.BOLD, 16));
btnCancel.setBounds(712, 622, 115, 29);
add(btnCancel);
JLabel lblQnsNo = new JLabel("Question No. : ");
lblQnsNo.setFont(new Font("Tahoma", Font.BOLD, 16));
lblQnsNo.setBounds(76, 234, 151, 20);
add(lblQnsNo);
txtfQnsNo = new JTextField();
txtfQnsNo.setBounds(218, 228, 146, 26);
add(txtfQnsNo);
txtfQnsNo.setColumns(10);
txtfQnsNo.setText(new Integer(q.getQuestionNo()).toString());
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedUpdate();
} });
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 16));
btnUpdate.setBounds(572, 622, 115, 29);
add(btnUpdate);
}
//Create
private void actionPerformedAdd() {
// retrieve the user input from the text box/area provided
if (validateInput()) {
//amtSpend = Double.parseDouble(txtAmount.getText());
// create an object of expenses based on the input values
//Debugging? -> System.out.println(topic);
//***Refer to QuizDetails Entity Class for its constructor
QuizDetails e1 = new QuizDetails(Integer.parseInt(txtfQnsNo.getText()), txtfQnsDesc.getText(), txtfOp1.getText(),
txtfOp2.getText(), txtfOp3.getText(), txtfOp4.getText(), txtfCorrAns.getText(), topic, set);
// insert to database and check return value
if (QuizDetailsDA.createQuizDetails(e1)) { //Call Create method from QuizDetailsDA
System.out.print("Ok");
JOptionPane.showMessageDialog(myFrame,
"Record created successfully", "Alert",
JOptionPane.INFORMATION_MESSAGE);
// reset text field for next record.
txtfQnsNo.setText("");
txtfQnsDesc.setText("");
txtfOp1.setText("");
txtfOp2.setText("");
txtfOp3.setText("");
txtfOp4.setText("");
txtfCorrAns.setText("");
JPanel contentPane = new AdminQuizOverallPanel(myFrame, set,topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
} else
{
System.out.print("Error");
JOptionPane.showMessageDialog(myFrame,
"Database Error. Record not created.", "Alert",
JOptionPane.ERROR_MESSAGE);
}
}
}
private boolean validateInput() {
boolean result = false;
String msg = "";
result = true;
/*int msgType = JOptionPane.ERROR_MESSAGE;
// retrieve the user input from the text box/area provided
String dateSpend = txtDate.getText();
String cat = txtCategory.getText();
String amt = txtAmount.getText();
String cont = txtContent.getText();
if (dateSpend.length() != 10)
msg += "Please enter date in DD-MM-YYYY format.\n";
if (cat.length() == 0)
msg += "Please enter category.\n";
try {
Double.parseDouble(amt); // convert to double for amount
} catch (NumberFormatException e) {
msg += "Plese enter amount in decimal numbers.\n";
}
if (cont.length() == 0)
msg += "Please enter content.\n";
if (msg.length() == 0)
result = true;
else
JOptionPane.showMessageDialog(myFrame, msg, "Alert", msgType);
*/
return result;
}
//Update
public AdminCreateQnsPanel(JFrame mf,String action, QuizDetails e1){
this(mf, action);
txtfQnsNo.setText(new Integer(e1.getQuestionNo()).toString());
txtfQnsDesc.setText(e1.getQuestionDesc());
txtfOp1.setText(e1.getOption1());
txtfOp2.setText(e1.getOption2());
txtfOp3.setText(e1.getOption3());
txtfOp4.setText(e1.getOption4());
txtfCorrAns.setText(e1.getCorrectAnswer());
quizdetails = e1;
}
public AdminCreateQnsPanel(JFrame mf, String action) {
super(mf);
}
public void actionPerformedUpdate(){
int qnsNo = Integer.parseInt(txtfQnsNo.getText());
String qnsDesc = txtfQnsDesc.getText();
String op1 = txtfOp1.getText();
String op2 = txtfOp2.getText();
String op3 = txtfOp3.getText();
String op4 = txtfOp4.getText();
String corrAns = txtfCorrAns.getText();
//***Refer to QuizDetails Entity Class for its constructor
QuizDetails e1 = new QuizDetails(id1,qnsNo, qnsDesc, op1, op2, op3, op4, corrAns);
//Testing -> System.out.println("action performed update " + e1.getQuestionNo());
if(QuizDetailsDA.updateQuizDetails(e1)){ //Call Update method from QuizDetailsDA
JOptionPane.showMessageDialog(myFrame, "Record updated successfully", "Alert", JOptionPane.INFORMATION_MESSAGE);
txtfQnsNo.setEditable(false);
txtfQnsDesc.setEditable(false);
txtfOp1.setEditable(false);
txtfOp2.setEditable(false);
txtfOp3.setEditable(false);
txtfOp4.setEditable(false);
txtfCorrAns.setEditable(false);
}
else{
JOptionPane.showMessageDialog(myFrame, "Database Error. Record not updated.", "Alert", JOptionPane.ERROR_MESSAGE);
}
}
This is the class where JTable is shown.
package studyHelperApp.ui;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import model.QuizDetailsTableModel;
import studyHelperApp.dataAccess.QuizDetailsDA;
import studyHelperApp.entity.QuizDetails;
import javax.swing.JButton;
import javax.swing.JFrame;
import studyHelpersApp.ui.MasterPanel;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.ListSelectionModel;
import java.awt.Color;
public class AdminQuizOverallPanel extends MasterPanel {
private JTextField txtfSearch;
private JTable table;
private int set;
private String topic;
public static int id1;
private int id;
private void setTableModelFromDB(){
ArrayList <QuizDetails> result = QuizDetailsDA.retrieveAllQuizDetails(set,topic); //Call method from QuizDetailsDA
QuizDetailsTableModel model = new QuizDetailsTableModel(result);
table.setModel(model);
}
public void loadDataTable(){
setTableModelFromDB();
}
/**
* Create the panel.
* #wbp.parser.constructor
*/
public AdminQuizOverallPanel(JFrame mf) {
super(mf);
initComponents();
setBounds(100, 100, 900, 750);
setLayout(null);
JLabel lblDisplay = new JLabel("");
lblDisplay.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblDisplay.setBounds(550, 200, 287, 20);
add(lblDisplay);
JLabel lblSet = new JLabel("Set ");
lblSet.setBounds(49, 189, 58, 31);
lblSet.setFont(new Font("Tahoma", Font.BOLD, 30));
add(lblSet);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(15, 246, 847, 225);
add(scrollPane);
table = new JTable();
loadDataTable();
scrollPane.setViewportView(table);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedDelete();
}
});
btnDelete.setFont(new Font("Tahoma", Font.BOLD, 16));
btnDelete.setBounds(637, 502, 115, 29);
add(btnDelete);
JButton btnSearch = new JButton("Search");
btnSearch.setFont(new Font("Tahoma", Font.BOLD, 16));
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0){
lblDisplay.setText("You searched for: "+txtfSearch.getText());
}
});
btnSearch.setBounds(744, 160, 93, 29);
add(btnSearch);
txtfSearch = new JTextField();
txtfSearch.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_ENTER)
lblDisplay.setText("You searched for: "+txtfSearch.getText());
}
});
txtfSearch.setBounds(550, 161, 194, 26);
add(txtfSearch);
txtfSearch.setColumns(10);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedUpdate();
}
});
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 16));
btnUpdate.setBounds(372, 502, 115, 29);
add(btnUpdate);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminCreateQnsPanel(myFrame, set ,topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnAdd.setFont(new Font("Tahoma", Font.BOLD, 16));
btnAdd.setBounds(135, 502, 115, 29);
add(btnAdd);
JButton btnBack = new JButton("<Back");
btnBack.setFont(new Font("Tahoma", Font.BOLD, 16));
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminQuizSetNoPanel(myFrame, topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnBack.setBounds(70, 555, 115, 29);
add(btnBack);
JLabel lblQuizID = new JLabel(topic);
lblQuizID.setFont(new Font("Tahoma", Font.BOLD, 30));
lblQuizID.setBounds(156, 189, 147, 31);
add(lblQuizID);
JLabel lblSetNo = new JLabel("");
lblSetNo.setFont(new Font("Tahoma", Font.BOLD, 30));
lblSetNo.setBounds(107, 189, 31, 31);
add(lblSetNo);
}
public AdminQuizOverallPanel(JFrame mf, int set, String topic) {
super(mf);
this.set = set;
this.topic = topic;
initComponents();
setBounds(100, 100, 900, 750);
setLayout(null);
JLabel lblDisplay = new JLabel("");
lblDisplay.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblDisplay.setBounds(550, 200, 287, 20);
add(lblDisplay);
JLabel lblSet = new JLabel("Set");
lblSet.setBounds(49, 189, 93, 31);
lblSet.setFont(new Font("Tahoma", Font.BOLD, 30));
add(lblSet);
JLabel lblSetNo = new JLabel(Integer.toString(set));
lblSetNo.setBounds(107, 189, 31, 31);
lblSetNo.setFont(new Font("Tahoma", Font.BOLD, 30));
add(lblSetNo);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(15, 246, 847, 225);
add(scrollPane);
table = new JTable();
loadDataTable();
scrollPane.setViewportView(table);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedDelete();
}
});
btnDelete.setFont(new Font("Tahoma", Font.BOLD, 16));
btnDelete.setBounds(611, 502, 115, 29);
add(btnDelete);
JButton btnSearch = new JButton("Search");
btnSearch.setFont(new Font("Tahoma", Font.BOLD, 16));
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0){
lblDisplay.setText("You searched for: "+txtfSearch.getText());
//findQuizDetails();
}
});
btnSearch.setBounds(744, 160, 93, 29);
add(btnSearch);
txtfSearch = new JTextField();
txtfSearch.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_ENTER)
lblDisplay.setText("You searched for: "+txtfSearch.getText());
}
});
txtfSearch.setBounds(550, 161, 194, 26);
add(txtfSearch);
txtfSearch.setColumns(10);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedUpdate();
}
});
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 16));
btnUpdate.setBounds(365, 502, 115, 29);
add(btnUpdate);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminCreateQnsPanel(myFrame, set ,topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnAdd.setFont(new Font("Tahoma", Font.BOLD, 16));
btnAdd.setBounds(123, 502, 115, 29);
add(btnAdd);
JButton btnBack = new JButton("<Back");
btnBack.setFont(new Font("Tahoma", Font.BOLD, 16));
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminQuizSetNoPanel(myFrame, topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnBack.setBounds(70, 555, 115, 29);
add(btnBack);
JLabel lblQuizID = new JLabel(topic);
lblQuizID.setFont(new Font("Tahoma", Font.BOLD, 30));
lblQuizID.setBounds(156, 189, 147, 31);
add(lblQuizID);
}
private void initComponents() {
// TODO Auto-generated method stub
}
//Delete
public void actionPerformedDelete(){
System.out.println("performed delete 1****");
int rowSelected = table.getSelectedRow();
System.out.println("performed delete 2 *****"+ rowSelected);
if(rowSelected >= 0){
int resp = JOptionPane.showConfirmDialog(myFrame, "Confirm Delete?", "Confirmation", JOptionPane.YES_NO_CANCEL_OPTION);
if(resp == JOptionPane.YES_OPTION){
int selRowDel = (Integer)table.getModel().getValueAt(rowSelected, 0);
QuizDetailsDA.deleteQuizDetails(selRowDel); //Call Delete method from QuizDetailsDA
//QuizDetailsDA.retrieveAllQuizDetails();
setTableModelFromDB();
}
else {
JOptionPane.showMessageDialog(myFrame, "No record selected", "Alert", JOptionPane.ERROR_MESSAGE);
}
}
}
//Update
public void actionPerformedUpdate(){
int rowSelected = table.getSelectedRow();
if(rowSelected >= 0){
int id = (Integer)table.getModel().getValueAt(rowSelected, 0);
id1 = id;
QuizDetails quizdt = QuizDetailsDA.retrieveQuizDetailsById(id);
//Testing -> System.out.println("**** action performed update **: " + quizdt.getQuestionNo());
//Call method from AdminCreateQnsPanel(JFrame mf, QuizDetails q, int set, String topic) constructor
JPanel contentPane = new AdminCreateQnsPanel(myFrame,quizdt, set, topic);
//After adding set and topic to this above constructor, cancel button is working in AdminCreateQnsPanel
myFrame.getContentPane().removeAll();
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
else {
JOptionPane.showMessageDialog(myFrame, "No record selected", "Alert", JOptionPane.ERROR_MESSAGE);
}
}
}
Data access package
//retrieve quiz by id
public static QuizDetails retrieveQuizDetailsById(int id) {
// declare local variables
QuizDetails quizdetails = null;
ResultSet rs = null;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - connect to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "SELECT * FROM QuizDetails WHERE id=?";
pstmt = db.getPreparedStatement(dbQuery);
// step 3 - execute query
try {
pstmt.setInt(1,id);
rs = pstmt.executeQuery();
if (rs.next()) { // first record found
quizdetails = convertToQuizDetails(rs);
}
} catch (Exception e) {
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return quizdetails;
}
private static QuizDetails convertToQuizDetails(ResultSet rs) throws SQLException {
QuizDetails quizdetails;
int id = rs.getInt("id");
//String quizID = rs.getString("quizID");
//int setNo = rs.getInt("setNo");
int questionNo = rs.getInt("questionNo");
String questionDesc = rs.getString("questionDesc");
String option1 = rs.getString("option1");
String option2 = rs.getString("option2");
String option3 = rs.getString("option3");
String option4 = rs.getString("option4");
String correctAnswer = rs.getString("correctAnswer");
quizdetails = new QuizDetails(id, questionNo, questionDesc, option1, option2, option3, option4, correctAnswer );
return quizdetails;
}
//Update
public static boolean updateQuizDetails(QuizDetails quizdt) {
//declare local variables
boolean success = false;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
System.out.println("quiz details da ** 1a " + quizdt.getQuestionNo());
System.out.println("quiz details da ** 1b " + quizdt.getQuestionDesc());
//step 1 - establish connection to database
db.getConnection();
//step 2 - declare the SQL statement
//dbQuery = "UPDATE QuizDetails SET quizID = ?, setNo = ?, questionNo = ?, questionDesc = ?, option1 = ?, option2 = ?, option3 = ?, option4 =?, correctAnswer = ? WHERE id = ?";
dbQuery = "UPDATE QuizDetails SET questionNo = ?, questionDesc = ?, option1 = ?, option2 = ?, option3 = ?, option4 =?, correctAnswer = ? WHERE id= ?";
pstmt = db.getPreparedStatement(dbQuery);
System.out.println("quiz details da 2 ** " + quizdt.getQuestionNo());
//step 3 - to update record using executeUpdate method
try {
//pstmt.setInt(1, quizdt.getId());
//pstmt.setString(1, quizdt.getQuizID());
//pstmt.setInt(2, quizdt.getSetNo());
pstmt.setInt(1, quizdt.getQuestionNo());
pstmt.setString(2, quizdt.getQuestionDesc());
pstmt.setString(3, quizdt.getOption1());
pstmt.setString(4, quizdt.getOption2());
pstmt.setString(5, quizdt.getOption3());
pstmt.setString(6, quizdt.getOption4());
pstmt.setString(7,quizdt.getCorrectAnswer());
pstmt.setInt(8, quizdt.getId()); //Cannot be hard coded
System.out.println(quizdt.getId());
System.out.println("quiz details da 3 ** " + quizdt.getQuestionNo());
if (pstmt.executeUpdate() == 1)
success = true;
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
}
//step 4 - close connection
db.terminate();
return success;
}
For instance, I would want to update id 1 and it is updated successfully. However, when I want to update id 5 the updated items of id 5 would be then updated to id 1. Anyone encountered this problem while trying to update database?
You should probably provide more information for such question. It is hard to understand what is the context You are making update at. For example if You are using MySQL then You can solve this by fixing the query. Id should be used in where part and not in set part. Something like this should work fine:
UPDATE TABLE `users` SET `name` = 'John' WHERE `id` = 1;

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.

how to retrieve image from oracle and display in java frame

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.

Categories

Resources