Insert data to a table via Java GUI - java

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.

Related

Reading username and password from a text file and comparing them to textfields won't work eventhough they are the exact same

I need to create a login/register app that stores and retrieves users info from a file(.txt). So I am comparing the username and password from my file with the username and password from my textfields and eventhough they are the exact same the programm still will not match them.
It was working at some point but that was when I only had the Login class. After I finished the Register class it would not work eventhough I did not change anything in the Login class. I also tried to handwrite the txt just as I did the first time but no luck.
Login class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class Login extends JFrame implements ActionListener {
JButton SUBMIT;
JPanel panel;
JLabel label1, label2;
final JTextField text1, text2;
Login() {
label1 = new JLabel();
label1.setText("Username:");
text1 = new JTextField(15);
label2 = new JLabel();
label2.setText("Password:");
text2 = new JPasswordField(15);
SUBMIT = new JButton("SUBMIT");
panel = new JPanel(new GridLayout(3, 1));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(SUBMIT);
add(panel, BorderLayout.CENTER);
SUBMIT.addActionListener(this);
setTitle("LOGIN FORM");
}
public void actionPerformed(ActionEvent ae) {
File loginf = new File("filename.txt");
try {
Scanner read = new Scanner(loginf);
read.useDelimiter("\\n|,");
boolean login = false;
while (read.hasNext()) {
String user = read.next();
String pass = read.next();
String thisuser = text1.getText();
String thispass = text2.getText();
System.out.println(user + " " + pass);
System.out.println(thisuser + " " + thispass);
if (thisuser.equals(user) && thispass.equals(pass)) {
System.out.println("OOOKKKK");
login = true;
break;
}
}
if (login) {
NextPage page = new NextPage();
page.setVisible(true);
JLabel label = new JLabel("Welcome:" + text1.getText());
page.getContentPane().add(label);
setVisible(false);
} else {
JOptionPane.showMessageDialog(null, "Incorrect username or password");
text1.setText("");
text2.setText("");
}
read.close();
} catch (FileNotFoundException qwerty) {
JOptionPane.showMessageDialog(null, "Can't find a text file");
}
}
}
Parts of the Register class that I am using:
ln95: FileWriter out = null;
ln98: out = new FileWriter("filename.txt", true);
ln149:out.write(username + "," + pass);
ln150:out.write(System.getProperty("line.separator"));
Output from login:
student1 Student1
student2 Student2
student2 Student2
student2 Student2
student3 Student3
student2 Student2
The output that you have listed from login seems to have an extra carriage return that's why there seems to be an empty line. I assume this is coming from following piece of code.
System.out.println(user + " " + pass);
System.out.println(thisuser + " " + thispass);
If that is the case then thispass has one extra carriage return. That is causing the problem.

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

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

Data in 1 column is getting stored in different row than other columns

I'm Working on a swing project and i have a JDialogbox which contain two textfield and 1 combobox and two button "ok" and "cancel"and a Frame which have a text area which acts like Notepad and all of these Components are connected to Oracle Database whenever I insert data in JDialog and click on Ok the data is stored in database and the frame containing the text area is called and when i save the data written in textarea and click the save button the inserted Data is saved in different row in the Database but not in the same row as the JDialog components
import javax.swing.*;
import java.sql.*;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.*;
import java.awt.*;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class newmenu implements ActionListener {
JDialog jf;
JButton okBtn,CanBtn;
JTextField tf1,tf3;
JComboBox type;
JLabel prName,prType,prWritter;
JFrame frame;
JMenuBar menuBar;
JMenu file;
JMenuItem open, save, exit;
JFileChooser fileChooser;
JTextArea textArea;
public newmenu(){
jf = new JDialog();
jf.setTitle("New Report");
okBtn = new JButton("Ok");
okBtn.setBounds(10, 140, 60, 20);
okBtn.addActionListener(this);
CanBtn = new JButton("Cancel");
CanBtn.addActionListener(this);
CanBtn.setBounds(100, 140, 100, 20);
tf1 = new JTextField();
tf1.setBounds(150, 20, 100, 20);
String r_Type [] = {"Cosmetics","Pharametical","Medical"};
type = new JComboBox(r_Type);
type.setBounds(150, 60, 100, 20);
tf3 = new JTextField();
tf3.setBounds(150, 100, 100, 20);
prName = new JLabel("Report Name");
prName.setBounds(10, 20, 100, 20);
prType = new JLabel("Report type");
prType.setBounds(10,60,100,20);
prWritter = new JLabel("Report Written");
prWritter.setBounds(10,100,100,20);
jf.add(okBtn);
jf.add(CanBtn);
jf.add(tf1);
jf.add(type);
jf.add(tf3);
jf.add(prName);
jf.add(prType);
jf.add(prWritter);
jf.setSize(300, 200);
jf.setResizable(false);
jf.setLayout(null);
jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jf.setVisible(true);
}
public void notepad(){
frame = new JFrame();
frame.setTitle("Notepad");
file = new JMenu("File");
save = new JMenuItem("Save");
save.addActionListener(this);
exit = new JMenuItem("Exit");
exit.addActionListener(this);
textArea = new JTextArea();
fileChooser = new JFileChooser();
menuBar = new JMenuBar();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(textArea);
file.add(save);
file.add(exit);
menuBar.add(file);
frame.setJMenuBar(menuBar);
frame.setSize(800, 600);
frame.setVisible(true);
}
public void insert(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection con = DriverManager
.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","root");
Statement st = con.createStatement();
st.executeUpdate("insert into report (reportname, reporttype,clientname) VALUES('"
+ tf1.getText() + "','"
+ tf3.getText() + "','" + type.getSelectedItem()+ "')");
}
catch (Exception e1)
{
System.out.println("Exception:" + e1);
}
}
public void notepadinsert(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection con = DriverManager
.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","root");
Statement st = con.createStatement();
st.executeUpdate("insert into report (report) VALUES('"
+ textArea.getText() + "')");
}
catch (Exception e1)
{
System.out.println("Exception:" + e1);
}
}
public void actionPerformed(ActionEvent ev){
if(ev.getSource()==okBtn){
if( tf1.getText().trim().equals("")){
okBtn.setEnabled(false);
if(tf1.getText().hashCode() != 0){
okBtn.setEnabled(true);
}
}
else{
okBtn.setEnabled(true);
jf.dispose();
insert();
notepad();
}
}
else if(ev.getSource()==CanBtn){
System.exit(0);
}
else if(ev.getSource()==save){
notepadinsert();
}
else if(ev.getSource()==exit){
System.exit(0);
}
}
public static void main(String args[]){
new newmenu();
}
}
Use a flag to check if it's a first request.
private int flag=0;
...
insert(){
...
if(flag==0){
//insert command
flag=1;
}
else
{
//update here.
}
}
UPDATE:
A better way can be to check if the current user has done the update..You have to create a field (like user_name) because I cannot see that in your insert query .
insert(){
...
//search for the current record with user_name in DB
if(!found){
//insert command
}
else
{
//update here.
}
}
Chnged your code like this... In the insert() method now you have data to be stored... Store that data in database in one go... I have added System.out.println(); because i couldn't create an oracle database and this was only way to check if i am getting all the data needed...
You just write your code for inserting into the DataBase in the insert method and pass the values from the string array which i have used to print the values...
public void insert(String[] Str){ // Write your code for insertion
// of values in database
System.out.println(Str[0]);
System.out.println(Str[1]); // I just used these to check
System.out.println(Str[2]); // If i am getting correct values
System.out.println(Str[3]);
}
#Override
public void actionPerformed(ActionEvent ev){
String[] Data_To_Insert = new String[4];
if(ev.getSource()==okBtn){
if( tf1.getText().trim().equals("")){
okBtn.setEnabled(false);
if(tf1.getText().hashCode() != 0){
okBtn.setEnabled(true);
}
}
else{
okBtn.setEnabled(true);
jf.dispose();
notepad();
}
}
else if(ev.getSource()==CanBtn){
System.exit(0);
}
else if(ev.getSource()==save){
Data_To_Insert[0] = tf1.getText();
Data_To_Insert[1] = tf3.getText();
Data_To_Insert[2] = type.getSelectedItem().toString();
Data_To_Insert[3] = textArea.getText();
insert(Data_To_Insert);
}
else if(ev.getSource()==exit){
System.exit(0);
}
}
Also remember you have to create 4 columns to store the data...
Hoping it helped...

Insert data from applet textfield to mysql database - error

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.

MS Access Database not responding

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

Categories