I have been given a college assignment to insert data into a mysql table using java applets. When I press the submit button, the command prompt throws a lot of exceptions(pic attached) and no data is inserted into the table.
Following is my code:
//Student registration Form (using applets and awt controls)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.sql.*;
import java.util.*;
public class mysql4 extends Applet implements ActionListener{
Label l1 = new Label("Roll No. : ");
TextField t1 = new TextField("",10);
Label l2 = new Label("Name : ");
TextField t2 = new TextField("",20);
Label l3 = new Label("Gender : ");
CheckboxGroup radioGroup = new CheckboxGroup();
Checkbox r1 = new Checkbox("Male", radioGroup, false);
Checkbox r2 = new Checkbox("Female", radioGroup, true);
Label l4 = new Label("Hobbies : ");
Checkbox c1 = new Checkbox("Sports");
Checkbox c2 = new Checkbox("Cooking/Gardening");
Checkbox c3 = new Checkbox("Music");
Checkbox c4 = new Checkbox("Arts/Crafts");
Label l5 = new Label("Course Opted : ");
Choice l=new Choice();
Label l6 = new Label("FeedBack : ",Label.CENTER);
TextArea ta = new TextArea("",15,20);
Button b1 = new Button("Submit");
Button b2 = new Button("Reset");
public void init() {
l1.setAlignment(Label.CENTER);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(r1);
add(r2);
add(l4);
add(c1);
add(c2);
add(c3);
add(c4);
add(l5);
l.add("BCA");
l.add("MCA");
l.add("PGDCA");
add(l);
add(l6);
add(ta);
b1.addActionListener(this);
add(b1);
b2.addActionListener(this);
add(b2);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1){
try{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/sonoo?useSSL=false";
Class.forName(myDriver);
Connection con = DriverManager.getConnection(myUrl, "root", "12345678");
String query = "insert into details (RollNo, Name, Gender, Hobbies, Course, FeedBack)" + " values (?, ?, ?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setString (1, l1.getText());
ps.setString (2, l2.getText());
Checkbox chkr = radioGroup.getSelectedCheckbox();
ps.setString (3, chkr.getLabel());
Checkbox chk = radioGroup.getSelectedCheckbox();
ps.setString (4, chk.getLabel());
ps.setString (5, l.getSelectedItem());
ps.setString (6, ta.getText());
ps.execute();
con.close();
}catch(Exception ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}else if(e.getSource()==b2){
t1.setText(" ");
t2.setText(" ");
r1.setState(false);
r2.setState(true);
c1.setState(false);
c2.setState(false);
c3.setState(false);
c4.setState(false);
l.select("BCA");
ta.setText(" ");
}else{}
}
}
Output:
AppletLayout:
You're getting an AccessControlException when the driver is trying to read the file.encoding property. The applet needs to be given this permission for the driver to work.
Related
I want to add another column in mysql either by using java or manually in the mysql application. This is my java code and I need to add a column named book_id
package liblog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class AStudents extends JFrame {
private JTextField admissionnumber;
private JTextField firstname;
private JTextField lastname;
private JTextField surname;
private JTextField house;
private JTextField dome;
private JButton add;
private JButton back;
private static Connection conn;
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon("C:/Users/User/workspace/Login/src/liblog/parklands.png");
JPanel panel = new JPanel(new GridBagLayout());
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JLabel admissionNumber = new JLabel();
JLabel firstName = new JLabel();
JLabel lastName = new JLabel();
JLabel surName = new JLabel();
JLabel mainHouse = new JLabel();
JLabel mainDome = new JLabel();
AStudents(){
super("DR.RIBEIRO PARKLANDS SCHOOL");
setLayout(new FlowLayout(FlowLayout.LEFT,3,100));
setBounds(500,500,550,550);
setLocation(500,200);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container con = this.getContentPane();
con.setBackground(Color.GRAY);
con.add(panel);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
panel2.setLayout(new FlowLayout(FlowLayout.CENTER,3,10));/*X axis,Y axis*/
panel3.setLayout(new BoxLayout(panel,BoxLayout.LINE_AXIS));
panel.setBackground(Color.GRAY);
/* admissionNumber=new JLabel("Admission Number");
admissionNumber.setAlignmentX(0.0f);
admissionnumber = new JTextField("No",30);
admissionnumber.setAlignmentX(0.0f);*/
firstName=new JLabel("First Name");
firstName.setAlignmentX(0.0f);
firstname = new JTextField("Name",20);
firstname.setAlignmentX(0.0f);
lastName=new JLabel("Last Name");
lastName.setAlignmentX(0.0f);
lastname = new JTextField("Name",20);
lastname.setAlignmentX(0.0f);
surName=new JLabel("Surname");
surName.setAlignmentX(0.0f);
surname = new JTextField("Name",20);
surname.setAlignmentX(0.0f);
mainHouse=new JLabel("House");
mainHouse.setAlignmentX(0.0f);
house = new JTextField("House",20);
house.setAlignmentX(0.0f);
mainDome=new JLabel("Dome");
mainDome.setAlignmentX(0.0f);
dome = new JTextField("Dome",20);
dome.setAlignmentX(0.0f);
add = new JButton("Add Student");
back = new JButton("Back");
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Insert into SQL:
try {
PreparedStatement insert = conn.prepareStatement("INSERT INTO students (first_name, last_name, surname, house, dome) VALUES (?,?,?,?,?)");
insert.setString(1, firstname.getText());
insert.setString(2, lastname.getText());
insert.setString(3, surname.getText());
insert.setString(4, house.getText());
insert.setString(5, dome.getText());
insert.execute();
ABooks abooks = new ABooks();
dispose();
}
catch(Exception ex) {
System.out.println(ex);
}
}
});
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Admin admin = new Admin();
dispose();
}
});
//panel.add(admissionNumber);
//panel.add(admissionnumber);
panel.add(firstName);
panel.add(firstname);
panel.add(lastName);
panel.add(lastname);
panel.add(surName);
panel.add(surname);
panel.add(mainHouse);
panel.add(house);
panel.add(mainDome);
panel.add(dome);
panel.add(add);
panel.add(back);
try {
conn = getConnection();
createTable();
}
catch(Exception ex) {
System.out.println(ex);
}
setVisible(true);
}
/*public static void main(String[]args) throws Exception{new AStudents();
createTable();
}*/
//Table
public static void createTable() throws Exception{
try{
Connection conn = getConnection();
PreparedStatement create = conn.prepareStatement("CREATE TABLE IF NOT EXISTS students(id int NOT NULL AUTO_INCREMENT,first_name varchar(45),last_name varchar(45),surname varchar(320),house varchar(50),dome varchar(50),book_id varchar(50),PRIMARY KEY(id))");
create.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally {
System.out.println("System Updated");};
}
//EndofTable
//DB
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/students?useSSL=false";
String username = "root";
String password = "toor";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
}catch(Exception e){
System.out.println(e);
}
return null;
}
//DB
}
The application is giving me the following error which I cannot get rid of
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'borrow_id' in 'field list'
This is the other code http://www.rapidtables.com/tools/notepad.htm
In your SQL DB:
ALTER TABLE students ADD book_id varchar(50)
I'm guessing as to the datatype of the book_id.
Do you mean book_id or borrow_id? I don't see borrow_id in your code which is somewhat confusing and probably why you're getting down voted.
I am getting a bunch of error when I try to insert a new data to the table (Type data for each field and then click submit). It supposed to output the SQL insertion command (exactly the same on that used by Java) in the TextArea. How can I fix this problem? Am I missing something in my code? Here is my code:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
//This GUI interface is a place holder to be finished by students.
public class InsertPanel extends JPanel{
private Connection connection = null;
private Statement statement = null;
public JTextField isbnTextFld;
public JTextField authorTextFld;
public JTextField titleTextFld;
public JTextField priceTextFld;
public JTextArea textArea;
public JButton submitBtn;
public InsertPanel() {
setBackground(Color.yellow);
setPreferredSize(new Dimension(540, 500));
JPanel p = new JPanel();
p.setLayout(new GridLayout(5, 3));
JLabel isbnLabel = new JLabel("ISBN: ");
isbnTextFld = new JTextField(10);
JLabel authorLabel = new JLabel("Author: ");
authorTextFld = new JTextField(15);
JLabel titleLabel = new JLabel("Title: ");
titleTextFld = new JTextField(20);
JLabel priceLabel = new JLabel("Price: ");
priceTextFld = new JTextField(10);
submitBtn = new JButton("Submit");
ButtonListener buttonListener = new ButtonListener();
submitBtn.addActionListener(buttonListener);
textArea = new JTextArea(10, 30);
p.add(isbnLabel);
p.add(isbnTextFld);
p.add(authorLabel);
p.add(authorTextFld);
p.add(titleLabel);
p.add(titleTextFld);
p.add(priceLabel);
p.add(priceTextFld);
p.add(submitBtn);
p.add(textArea);
add(p, BorderLayout.NORTH);
add(textArea, BorderLayout.CENTER);
}
public class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
try {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost/books", "root", "admin");
statement = connection.createStatement();
String isbn = isbnTextFld.getText();
String title = titleTextFld.getText();
String author = authorTextFld.getText();
String price = priceTextFld.getText();
String sql = "Insert('" + (isbn) + "' + '" + (title) + "' + '" + (author) + "' + '" + (price)
+ "')";
statement.executeUpdate(sql);
} catch (SQLException sqlException){
sqlException.printStackTrace();
}
}
}
}
create table books
( isbn char(13) not null primary key,
author char(30),
title char(60),
price float(4,2)
);
insert into books values
("0-672-31697-8", "Michael Morgan", "Java 2 for Professional Developers", 34.99),
("0-672-31745-1", "Thomas Down", "Installing Debian GNU/Linux", 24.99),
("0-672-31509-2", "Pruitt, et al.", "Teach Yourself GIMP in 24 Hours", 24.99),
("0-672-31769-9", "Thomas Schenk", "Caldera OpenLinux System Administration Unleashed", 49.99);
Thanks for your hepl!!!
My first suggestion is that you should learn more SQL Syntax before attempting further. I am stating this because the valid SQL insert statement should look like:
INSERT INTO <table_name> VALUES (<value1>, <value2>, ....);
OR
INSERT INTO <table_name> (<column_1>, <column_2>, ...) VALUES (<value1>, <value2>, ....);
Also you should try to use PreparedStatement instead of Statement to dynamically set the values to the statement. And go through JDBC in details.
What I am trying to do is to add data on mysql database using my applet page. my idea is to fill up the textfields then when i hit the save button all the text's will add to mySQL database. But i'm having an error saying
Access Denied: java.security.AccessControlException:access denied
(java.io.FilePermision "\C:\Program Files(x86)\MySQL\mysql-connector-java-5.1.30\mysql-connector-java-5.1.30-bin.jar" "read")
thank you in advance. here's my code: :((
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.JApplet;
import java.sql.*;
import java.net.*;
public class AddBook extends JApplet
{
JButton btnSave, btnCancel;
JLabel lblIsbn, lblTitle, lblCategory, lblAuthor, lblYPublish, lblPublisher, lblCopies, lblYear, lblMsg1;
JTextField txtTitle, txtCategory;
JTextField txtIsbn, txtAuthor, txtPublisher, txtCopies, txtYear;
String ttitle, tauthor, tpublisher, tcategory, tisbn, tyear, tqty;
public void init()
{
Font fonttxt = new Font("Calibri", Font.PLAIN, 16);
Font fontlbl = new Font("Calibri",Font.BOLD, 14);
Font fontbtn = new Font("Calibri",Font.BOLD, 16);
Font fontTitle = new Font("Arial ",Font.BOLD,30);
setLayout(null);
setSize(410, 400);
setBackground(Color.gray);
btnSave = new JButton("Save");
btnSave.setFont(fontbtn);
btnCancel = new JButton("Cancel");
btnCancel.setFont(fontbtn);
lblMsg1 = new JLabel ("ADD BOOK");
lblMsg1.setFont(fontbtn);
lblIsbn = new JLabel("ISBN :");
lblIsbn.setFont(fontlbl);
lblTitle = new JLabel ("Title :");
lblTitle.setFont(fontlbl);
lblCategory = new JLabel ("Category :");
lblCategory.setFont(fontlbl);
lblAuthor = new JLabel ("Author :");
lblAuthor.setFont(fontlbl);
lblYear = new JLabel ("Year Published :");
lblYear.setFont(fontlbl);
lblPublisher = new JLabel ("Publisher :");
lblPublisher.setFont(fontlbl);
lblCopies = new JLabel ("Number of Copies :");
lblCopies.setFont(fontlbl);
JTextField txtIsbn = new JTextField ("",100);
txtIsbn.setFont(fonttxt);
JTextField txtTitle = new JTextField ("",100);
txtTitle.setFont(fonttxt);
JTextField txtCategory = new JTextField ("",100);
txtCategory.setFont(fonttxt);
JTextField txtAuthor = new JTextField ("",100);
txtAuthor.setFont(fonttxt);
JTextField txtPublisher = new JTextField ("",100);
txtPublisher.setFont(fonttxt);
JTextField txtCopies = new JTextField ("",100);
txtCopies.setFont(fonttxt);
JTextField txtYear = new JTextField ("",100);
txtYear.setFont(fonttxt);
lblMsg1.setBounds(10,10,200,40);
lblIsbn.setBounds(10,50,250,30);
txtIsbn.setBounds(130,50,250,30);
lblTitle.setBounds(10,90,250,30);
txtTitle.setBounds(130,90,250,30);
lblCategory.setBounds(10,130,250,30);
txtCategory.setBounds(130,130,250,30);
lblAuthor.setBounds(10,165,250,30);
txtAuthor.setBounds(130,165,250,30);
lblPublisher.setBounds(10,200,250,30);
txtPublisher.setBounds(130,200,250,30);
lblCopies.setBounds(10,240,250,30);
txtCopies.setBounds(130,240,250,30);
lblYear.setBounds(10,280,250,30);
txtYear.setBounds(130,280,250,30);
btnSave.setBounds(40,320,150,35);
btnCancel.setBounds(200,320,150,35);
add(lblMsg1);
add(txtIsbn);
add(txtTitle);
add(txtCategory);
add(txtAuthor);
add(txtPublisher);
add(txtCopies);
add(txtYear);
add(lblIsbn);
add(lblTitle);
add(lblCategory);
add(lblAuthor);
add(lblPublisher);
add(lblCopies);
add(lblYear);
add(btnSave);
add(btnCancel);
tisbn = txtIsbn.getText();
tyear = txtYear.getText();
tqty = txtCopies.getText();
ttitle = txtTitle.getText();
tauthor = txtAuthor.getText();
tcategory = txtCategory.getText();
tpublisher = txtPublisher.getText();
btnSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Connection con = null;
//Statement st = null; 1
PreparedStatement pstmt;
Connection con;
if(ae.getSource() == btnSave)
{
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/library_system", "root", "password");
con.setAutoCommit(false);
pstmt = con.prepareStatement ("INSERT INTO book_records VALUES (?, ?, ?, ?, ?, ?, ?)");
pstmt.setString(1, tisbn);
pstmt.setString(2, ttitle);
pstmt.setString(3, tauthor);
pstmt.setString (4, tyear);
pstmt.setString(5, tpublisher);
pstmt.setString(6, tcategory);
pstmt.setString(7, tqty);
pstmt.executeUpdate();
con.commit();
pstmt.close();
}
catch(Exception err)
{
JOptionPane.showMessageDialog(null, "Access Denied: "+err );
}
}
}
}
});
}
}
Could you please try the mysql connection as
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
I think you are missing port.
The error says simply "Access denied" problem from your Java program to the directory where MySQL jar exists.
You shouldn't link (reference) jar file in another directory from Java application.
The problem can be simply solved by adding the required mysql-connector-java-5.1.30-bin.jar to your application's class path.
I am retrieving details from table made in MS Access Database.
User enters some name
(being same name as present in table) in Textfield , then by hitting on submit button, details like FName,Studentid,Branch,Year,Semester,Email and Contact No is displayed.
My Java File is getting compiled correctly, but fetching details from table is not successfull.
The code is:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.io.*;
class Data extends JFrame
{
JFrame f;
JTabbedPane t;
Data()
{
f = new JFrame("Data");
f.setBounds(0,0,1300,500);
t = new JTabbedPane();
t.addTab("View", new View());
f.add(t);
f.setVisible(true);
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
Data data = new Data();
}
}
class View extends JPanel implements ActionListener
{
JLabel id,l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12;
JButton b1;
JTextField tf1;
JPanel p1,p2;
View()
{
setLayout(null);
p1 = new JPanel();
p1.setBounds(0,0,1300,100);
p1.setBackground(Color.red);
p2 = new JPanel();
p2.setLayout(null);
p2.setBounds(0,100,1300,400);
p2.setBackground(Color.blue);
id=new JLabel("Student Name");
id.setBounds(500,100,100,50);
b1=new JButton("SUBMIT");
b1.setBounds(600,150,100,50);
tf1=new JTextField(20);
tf1.setBounds(600,100,100,50);
p1.add(id);
p1.add(tf1);
b1.addActionListener(this);
p1.add(b1);
add(p1);
add(p2);
l1=new JLabel();
l2=new JLabel();
l3=new JLabel();
l4=new JLabel();
l5=new JLabel();
l6 = new JLabel();
l7=new JLabel("FName");
l8=new JLabel("Branch");
l9=new JLabel("Year");
l10=new JLabel("Semester");
l11=new JLabel("Email");
l12=new JLabel("Contact No");
l1.setBounds(700,10,100,20);
l2.setBounds(700,40,100,20);
l3.setBounds(700,70,100,20);
l4.setBounds(700,100,100,20);
l5.setBounds(700,130,100,20);
l6.setBounds(700,160,100,20);
l7.setBounds(500,10,100,20);
l8.setBounds(500,40,100,20);
l9.setBounds(500,70,100,20);
l10.setBounds(500,100,100,20);
l11.setBounds(500,130,100,20);
l12.setBounds(500,160,100,20);
p2.add(l1);
p2.add(l2);
p2.add(l3);
p2.add(l4);
p2.add(l5);
p2.add(l6);
p2.add(l7);
p2.add(l8);
p2.add(l9);
p2.add(l10);
p2.add(l11);
p2.add(l12);
p1.setVisible(true);
p2.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String nm="0",br="0",yr ="0",sm="0",em="0",ph="0";
int p=0;
if(ae.getSource()==b1)
{
try
{
String ss=tf1.getText();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("JDBC:ODBC:MS Access Database","","");
Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=st.executeQuery("Select * from information where FName= "+ss+" ");
System.out.println(rs);
while(rs.next())
{
nm=rs.getString("FName");
br=rs.getString("Branch");
yr=rs.getString("Year");
sm=rs.getString("Semester");
em=rs.getString("Email");
ph=rs.getString("Contact No");
p=Integer.parseInt(ph);
l1.setText(nm);
l2.setText(br);
l3.setText(yr);
l4.setText(sm);
l5.setText(em);
l6.setText(ph);
}
con.close();
}
catch(Exception e)
{
}
}
}
}
Please help what is wrong in code.....
When you "glued together" your SQL statement you didn't put any quotes around the string value in the WHERE clause. However, you shouldn't be "gluing together" SQL statements anyway. You should be using a parameter query, something like this
PreparedStatement st = con.prepareStatement(
"Select * from information where FName=?",
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
st.setString(1, ss);
ResultSet rs = st.executeQuery();
I have this code in Java Swings which creates 2 frames.The first frame contains 4 text fields(roll no,name,class,section) leaving the text fields blank I click on the search button in the 1st frame,another frame opens with all my table records in the database.Once I select a record(or the row) all the details of it appear in the 1st frame,i.e roll no,class,name and section get populated.
Right now I am using the search button to go to the next frame.What should I do so that the action is performed once I click on the roll no. text field instead of the search button?
This is the code:
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.Vector;
import java.awt.event.*;
public class barcoder1 implements ActionListener{
JFrame frame,frame1;
JTextField textbox,textbox1,textbox2,textbox3,textbox4,textbox5,textbox6,textbox7,textbox8;
JLabel label,label1,label2,label3,label4,label5,label6,label7,label8;
JButton button;
JPanel panel;
static JTable table;
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String userName = "root";
String password = "root";
String[] columnNames = {"Roll No", "Name", "Class", "Section"};
public void createUI()
{
frame = new JFrame("Database Search Result");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
textbox = new JTextField();
textbox.setBounds(120,30,150,20);
label=new JLabel("Roll No.");
label.setBounds(10, 30, 100, 20);
textbox1 = new JTextField();
textbox1.setBounds(120,50,150,20);
label1=new JLabel("Name");
label1.setBounds(10, 50, 100, 20);
textbox2 = new JTextField();
textbox2.setBounds(120,70,150,20);
label2=new JLabel("Class");
label2.setBounds(10, 70, 100, 20);
textbox3 = new JTextField();
textbox3.setBounds(120,90,150,20);
label3=new JLabel("Section");
label3.setBounds(10, 90, 100, 20);
button = new JButton("search");
button.setBounds(120,230,150,20);
button.addActionListener(this);
frame.add(textbox);
frame.add(label);
frame.add(textbox1);
frame.add(label1);
frame.add(textbox2);
frame.add(label2);
frame.add(textbox3);
frame.add(label3);
frame.add(button);
frame.setVisible(true);
frame.setSize(500, 400);
}
public void actionPerformed(ActionEvent ae)
{
button = (JButton)ae.getSource();
System.out.println("Showing Table Data.......");
showTableData();
}
public void showTableData()
{
frame1 = new JFrame("Database Search Result");
//frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
DefaultTableModel model = new DefaultTableModel(){
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
final JTable table = new JTable(model);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int row = table.getSelectedRow();
System.out.println("Selecte table row = " + row);
if (row != -1) {
int modelRow = table.convertRowIndexToModel(row);
System.out.println("Selecte model row = " + row);
Vector data = (Vector) ((DefaultTableModel) table.getModel()).getDataVector().get(modelRow);
textbox.setText(data.get(0).toString());
textbox1.setText(data.get(1).toString());
textbox2.setText(data.get(2).toString());
textbox3.setText(data.get(3).toString());
}
}
});
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
if (table.getSelectedRow() != -1) {
SwingUtilities.getWindowAncestor(table).dispose();
}
}
}
});
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
String textvalue = textbox.getText();
String roll= "";
String name= "";
String cl = "";
String sec = "";
try
{
Class.forName(driverName);
Connection con = DriverManager.getConnection(url, userName, password);
//String sql = "select * from student where rollno = "+textvalue;
String sql="select * from student";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int i =0;
while(rs.next())
{
roll = rs.getString("rollno");
name = rs.getString("name");
cl = rs.getString("class");
sec = rs.getString("section");
model.addRow(new Object[]{roll, name, cl, sec});
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage(),"Error",
JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(400,300);
}
public static void main(String args[])
{
barcoder1 sr = new barcoder1();
sr.createUI();
}
}