I'm Riya a B.Tech. student and i have to make a corejava project on the topic COLLEGE MANAGEMENT SYSTEM . I have created the required database using MS Access. I m facing problem in a code which i m attaching here. Actually i want to update a data in the data base so i have made 2 frames in one of them Roll no. is asked when it is entered then the 2nd frame opens and asks Enter Marks to be updated...when i enter the marks to be updated then a dialogue box opens shoing "Marks Updated Successfully". Till here i don't have any problem..the problem is when i open the database i see that actually the Marks is not updated there.So please please please somebody help me solving this problem.
The code is as follows:
1ST FRAME
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
class MyFrame03 extends JFrame implements ActionListener {
JLabel l1;
JTextField t1;
JPanel p1, p2;
JButton b1;
Connection con;
PreparedStatement pst;
String s1;
MyFrame03() {
setLayout(new GridLayout(4, 1));
setTitle("Enter Data Required");
setBackground(Color.blue);
l1 = new JLabel("Roll no");
t1 = new JTextField(12);
p1 = new JPanel();
p2 = new JPanel();
b1 = new JButton("SUBMIT");
p1.add(l1);
p1.add(t1);
p2.add(b1);
add(p1, "Center");
add(p2, "South");
b1.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("Jdbc:Odbc:dsn3");
if (con != null)
System.out.println("Connection Established");
}
catch (Exception e) {
System.out.println("exception");
}
}
public void actionPerformed(ActionEvent e1) {
if (e1.getSource() == b1) {
s1 = t1.getText();
try {
pst = con.prepareStatement("insert into stud values(?)");
pst.setString(1, s1);
pst.executeUpdate();
con.commit();
con.close();
}
catch (SQLException e) {
System.out.println("except1");
}
MyFrame04 m1 = new MyFrame04(s1);
dispose();
}
}
public static void main(String s[]) throws SQLException {
MyFrame03 m1 = new MyFrame03();
}
}
2nd FRAME
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
class MyFrame04 extends JFrame implements ActionListener {
JLabel l1;
JTextField t1;
JPanel p1, p2;
JButton b1;
String s1, s2;
Connection con;
PreparedStatement pst;
public MyFrame04(String s1) {
this.s1 = s1;
setLayout(new GridLayout(4, 1));
setTitle("Update Marks");
setBackground(Color.blue);
l1 = new JLabel("Enter Marks");
t1 = new JTextField(12);
b1 = new JButton("SUBMIT");
p1 = new JPanel();
p2 = new JPanel();
p1.add(l1);
p1.add(t1);
p2.add(b1);
add(p1, "Center");
add(p2, "South");
b1.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("Jdbc:Odbc:dsn3");
if (con != null)
System.out.println("Connection Established");
}
catch (Exception e) {
System.out.println("exception");
}
}
public void actionPerformed(ActionEvent e1) {
if (e1.getSource() == b1) {
s2 = t1.getText();
try {
pst = con.prepareStatement("UPDATE stud set Marks=? WHERE Roll no=?");
pst.setString(1, s2);
pst.setString(2, s1);
pst.executeUpdate();
con.commit();
con.close();
}
catch (SQLException e) {
System.out.println("except1");
}
JOptionPane.showMessageDialog(this, "Marks updated succesfully");
dispose();
}
}
}
Thankyou
Does your database access code work without Swing? The simplest way to see this would be something like:
class HelloDatabase {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("Jdbc:Odbc:dsn3");
if (con != null) {
int marks = 1, roll = 1; // or whatever (your data here)
System.out.println("Connection Established");
PreparedStatement pst = con.prepareStatement("UPDATE stud SET marks=? WHERE roll_num=?");
pst.setString(1, marks);
pst.setString(2, roll);
pst.executeUpdate();
con.commit();
con.close();
}
}
catch (Exception e) {
System.out.println("exception");
}
}
}
If this gets a handle and accesses your database properly, you're in luck.
By the way -- and this may actually be your issue -- I noticed that your SQL query from the original post had an ambiguity in it:
UPDATE stud set Marks=? WHERE Roll no=?
"Roll no" would not get recognized a valid SQL field, as far as I understand -- these should be a single 'word' (like 'roll', 'roll_num' or even 'RollNum' -- but I don't think a name like 'Roll no' would work here.)
Related
Now I have seen a few of these questions here but my problem is a bit different. I have created a Create Account page and Login page. I have made a database in MYSQL where the various usernames and corresponding passwords are stored. I created an account using the create account page and then checked through the Login page and saw that it was working. But then I tried to write a code where automatically a table is created in MYSQL after the corresponding account is created. But I get the above error. I will show you my Login and Create Account pages.
LOGIN:-
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.*;
public class Login extends Frame implements ActionListener, WindowListener
{
Label l1,l2,l3;
JTextField t1;
JPasswordField p1;
JButton b0,b1;
String url = "jdbc:mysql://localhost:3306/database1";
String user = "root";
String password = "Newyear2016!";
char[] s2;
String s1,s3;
Login()
{
addWindowListener(this);
setTitle("Login");
setSize(500,500);
setLayout(null);
setVisible(true);
l3 = new Label("Login");
l3.setBounds(120,50,300,50);
add(l3);
Font myFont1 = new Font("Helvetica",Font.ITALIC,30);
l3.setFont(myFont1);
l1 = new Label("User Name: ");
l1.setBounds(50,150,100,50);
add(l1);
l2 = new Label("Password: ");
l2.setBounds(50,250,100,50);
add(l2);
t1 = new JTextField();
p1 = new JPasswordField();
t1.setBounds(170,150,250,50);
p1.setBounds(170,250,250,50);
add(t1);
add(p1);
t1.addActionListener(this);
p1.addActionListener(this);
b0 = new JButton("Login");
b0.setBounds(170,350,100,50);
add(b0);
b0.addActionListener(this);
b1 = new JButton("Go Back");
b1.setBounds(300,350,100,50);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
s1 = t1.getText();
s2 = p1.getPassword();
s3 = new String(s2);
Object o = e.getSource();
if(o == b1)
{
dispose();
Home h = new Home();
}
mainLoop:
if(o == b0)
{
try
{
Connection myConn =
DriverManager.getConnection(url,user,password);
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("select * from login");
while(myRs.next())
{
if(s1.equals(myRs.getString("usname"))&&s3.equals(myRs.getString("pwd")))
{
System.out.println("Username Found");
System.out.println("Password Found");
JOptionPane.showMessageDialog(null,"Login Successful:
"+s1 );
break mainLoop;
}
}
JOptionPane.showMessageDialog(null,"Wrong Username/Password");
}
catch(Exception exc)
{
exc.printStackTrace();
}
}
}
public void windowClosing(WindowEvent e)
{
dispose();
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
}
Please tell me what I am doing wrong. I have checked that I have provided the right password. So that is not the problem.
CREATE ACCOUNT :-
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.*;
public class Login extends Frame implements ActionListener, WindowListener
{
Label l1,l2,l3;
JTextField t1;
JPasswordField p1;
JButton b0,b1;
String url = "jdbc:mysql://localhost:3306/database1";
String user = "root";
String password = "Newyear2016!";
char[] s2;
String s1,s3;
Login()
{
addWindowListener(this);
setTitle("Login");
setSize(500,500);
setLayout(null);
setVisible(true);
l3 = new Label("Login");
l3.setBounds(120,50,300,50);
add(l3);
Font myFont1 = new Font("Helvetica",Font.ITALIC,30);
l3.setFont(myFont1);
l1 = new Label("User Name: ");
l1.setBounds(50,150,100,50);
add(l1);
l2 = new Label("Password: ");
l2.setBounds(50,250,100,50);
add(l2);
t1 = new JTextField();
p1 = new JPasswordField();
t1.setBounds(170,150,250,50);
p1.setBounds(170,250,250,50);
add(t1);
add(p1);
t1.addActionListener(this);
p1.addActionListener(this);
b0 = new JButton("Login");
b0.setBounds(170,350,100,50);
add(b0);
b0.addActionListener(this);
b1 = new JButton("Go Back");
b1.setBounds(300,350,100,50);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
s1 = t1.getText();
s2 = p1.getPassword();
s3 = new String(s2);
Object o = e.getSource();
if(o == b1)
{
dispose();
Home h = new Home();
}
mainLoop:
if(o == b0)
{
try
{
Connection myConn =
DriverManager.getConnection(url,user,password);
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("select * from login");
while(myRs.next())
{
if(s1.equals(myRs.getString("usname"))&&s3.equals(myRs.getString("pwd")))
{
System.out.println("Username Found");
System.out.println("Password Found");
JOptionPane.showMessageDialog(null,"Login Successful:
"+s1 );
break mainLoop;
}
}
JOptionPane.showMessageDialog(null,"Wrong Username/Password");
}
catch(Exception exc)
{
exc.printStackTrace();
}
}
}
public void windowClosing(WindowEvent e)
{
dispose();
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
}
#Edit :- I am sorry I forgot to provide the Create Account Page which was the problem. Can you please kindly go through it?
Some of your code is not in the code block so its hard to read but did you load the driver class?
String url="jdbc:mysql://localhost:3306/database1";
String userName="root";
String password="Newyear2016!";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection(url,username,password);
Here i am trying to retrieve a image stored in BLOB format and storing it in another table in the same BLOB format only! And one more issue is this that i have a JFrame named WelcomeStaffs from which i have to access the JTextField named subject_txt and staff_txt values and store it in the database.. But those are only blank! Not getting printed in the output, while i print it!
Here is the code of the FaceRecognizer class..
import static cern.jet.math.Bessel.i1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import facedetection.*;
import com.googlecode.javacv.*;
import com.googlecode.javacv.cpp.*;
import com.googlecode.javacpp.Loader;
import com.mysql.jdbc.Connection;
import java.sql.Blob;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FaceRecognizer extends JFrame
{
// GUI components
private FaceRecogPanel facePanel;
private JButton recogBut;
private JTextField nameField; // where the name (and distance info) appears
private JButton done;
private JButton exit;
public FaceRecognizer()
{
super("Face Recognizer");
FaceRecognizer fac;
Container c = getContentPane();
c.setLayout( new BorderLayout() );
// Preload the opencv_objdetect module to work around a known bug.
Loader.load(opencv_objdetect.class);
facePanel = new FaceRecogPanel(this); // the sequence of pictures appear here
c.add( facePanel, BorderLayout.CENTER);
// button for recognizing a highlighted face
done = new JButton("Done");
recogBut = new JButton("Recognize Face");
recogBut.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e)
{ nameField.setText("");
recogBut.setEnabled(false);
facePanel.setRecog();
}
});
done.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
WelcomeStaffs wc = new WelcomeStaffs();
Connection con = null;
try{
String url = "jdbc:mysql://localhost:3306/facedetection";
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Conncection Success");
con = (Connection) DriverManager.getConnection(url, "root", "2204");
System.out.println("Database Connected");
}
catch(Exception ex)
{
System.out.println("Exception = "+ex);
}
String nm = nameField.getText().toUpperCase();
String name ="",course="";
System.out.println("Hello im till here!!");
String subject = wc.subject_txt.getText();
String staff = wc.staff_txt.getText();
String day = wc.day_txt.getText();
String date = wc.date_txt.getText();
String time = wc.time_txt.getText();
int roll_no = 0;
System.out.println(subject+staff);
String sql = "SELECT roll_no,name,course,photo FROM students WHERE name=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,nm);
ResultSet rs = ps.executeQuery();
while(rs.next()) //retrieving values from database and storing it!
{
roll_no = rs.getInt("roll_no");
name = rs.getString("name");
course = rs.getString("course");
byte[]imagedata = rs.getBytes("photo");
image = Toolkit.getDefaultToolkit().createImage(imagedata);
format = new ImageIcon(image);
System.out.println("Retrieved Data!!!!!!!");
}
} catch (SQLException ex) {
Logger.getLogger(FaceRecognizer.class.getName()).log(Level.SEVERE, null, ex);
}
try{
if(roll_no == 0 || name.equals("") || course.equals(""))
{
System.out.println("EMPTY");
}
else
{
sql = "INSERT INTO attendance(roll_no, name, course, subject, staff, day, time, date, photo) VALUES(?,?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql);
ps1.setInt(1,roll_no);
ps1.setString(2,name);
ps1.setString(3,course);
ps1.setString(4,subject);
ps1.setString(5,staff);
ps1.setString(6,day);
ps1.setString(7,time);
ps1.setString(8,date);
ps1.setBlob(9, (Blob) format);
int i1 = ps1.executeUpdate();
JOptionPane.showMessageDialog(null,i1+" Data Inserted");
}
}
catch(Exception ec)
{
System.out.println(""+ec);
}
}
});
nameField = new JTextField(20); // for the name of the recognized face
nameField.setEditable(false);
JPanel p = new JPanel();
p.add(recogBut);
p.add( new JLabel("Name: "));
p.add( nameField);
p.add(done);
c.add(p, BorderLayout.SOUTH);
addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ facePanel.closeDown(); // stop snapping pics
/*Attendance_Chart ac = new Attendance_Chart();
ac.setVisible(true);*/
System.exit(0);
}
});
pack();
setResizable(false);
setVisible(true);
} // end of FaceRecognizer()
public void setRecogName(final String faceName, final String dist)
// update face name and its distance in the nameField; called from panel
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{ nameField.setText( faceName);
recogBut.setEnabled(true);
}
});
} // end of setRecogName()
// -------------------------------------------------------
public static void main( String args[] )
{
new FaceRecognizer();
}
public ImageIcon format = null;
public Image image = null;
public Blob blob = null;
}
// end of FaceRecognizer class
Here is the output i get!
Conncection Success for Staffs
detection/recognition duration: 9ms
Database Connected for Staffs
Table Created
Conncection Success
Database Connected
Hello im till here!!
Retrieved Data!!!!!!!
java.lang.ClassCastException: javax.swing.ImageIcon cannot be cast to `java.sql.Blob`
Please help!
Thank you!
The only thing remotely similar to my issue that I could find was this, however his problem seemed to be from a user error.
Reset cursor position after ResultSet updateRow
My problem is the following: After updating a row I am not able to access any other rows in my ResultSet. The update itself works fine, but if I want to continue I have to restart the application.
Here's the code:
package database;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Gui extends MyDB {
JFrame f;
JLabel FName;
JLabel LName;
JLabel Age;
JTextField t;
JTextField t2;
JTextField t3;
JButton next = new JButton("next");
JButton update = new JButton("Update");
public Gui() {
frame();
start();
btnAction();
}
public void frame() {
f = new JFrame();
f.setVisible(true);
f.setSize(680, 480);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FName = new JLabel("Name");
LName = new JLabel("Anrede");
Age = new JLabel("age");
t = new JTextField(10);
t2 = new JTextField(10);
t3 = new JTextField(10);
JPanel p = new JPanel();
p.add(FName);
p.add(t);
p.add(LName);
p.add(t2);
p.add(Age);
p.add(t3);
p.add(b1);
p.add(update);
public void btnAction() {
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
});
update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String FName = t.getText();
String LName = t2.getText();
String Age = t3.getText();
try {
System.out.println(rs.getRow());
rs.updateString("FName", FName);
rs.updateString("LName", LName);
rs.updateString("Age", Age);
rs.updateRow();
//System.out.println(rs.getString("FName"));
System.out.println(rs.getRow());
JOptionPane.showMessageDialog(null, "Record updated ");
} catch (Exception ex) {
System.out.println("no");
}
}
});
}
public void start() {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
}
Also:
package database;
import java.sql.*;
public class MyDB {
Connection con;
Statement st;
ResultSet rs;
public MyDB() {
connect();
}
public void connect() {
try {
String db = "jdbc:ucanaccess://Datenbank1.accdb";
con = DriverManager.getConnection(db);
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "select * from Tabelle1";
rs = st.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace(System.out);
}
}
public static void main(String[] args) {
new Gui();
}
}
Output of System.out.println(rs.getRow()); is '0'.
If I want to click on the 'next' button after updating, the message "no next records" is displayed.
I have tried using rs.first(), rs.beforeFirst() and rs.isBeforeFirst(), none of which have worked.
If it helps, I am following this tutorial, which does not run into the same problem:
https://www.youtube.com/watch?v=NPV2o6YjP10
private void update_table(){
try{
DefaultTableModel df=(DefaultTableModel)jTable1.getModel();
Conn c=new Conn();
Statement s=c.createConn().createStatement();
// df.getDataVector().removeAllElements();
String sql="Select * from leave_taken";
ResultSet rs=s.executeQuery(sql);
while(rs.next()){
Vector v=new Vector();
df.addRow(v);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
} catch (Exception e) {
e.printStackTrace();
}
This is what i wrote. i want to lad data to the table by this method. but it loads only the table headings. how can i load table data to the table? Is there some thing need to add to this code?
Your v variable happens to be empty vector when you do df.addRow(v). Seems like you don't need df in your code.
Full example working with data
package javaapplication2;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import net.proteanit.sql.DbUtils;
public class JavaApplication2
{
public static void main(String[] args)
{
Runnable r = new Runnable()
{
#Override
public void run()
{
JFrame f = new JFrame();
JPanel p = new JPanel();
f.setContentPane(p);
f.setPreferredSize(new Dimension(600, 600));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTable t = new JTable();
p.add(new JScrollPane(t), BorderLayout.CENTER);
JButton b = new JButton("Run");
p.add(b, BorderLayout.WEST);
b.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection c = DriverManager.getConnection("jdbc:sqlserver://localhost;integratedSecurity=true;databaseName=stackoverflow");
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM leave_taken");
t.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (SQLException es)
{
es.printStackTrace();
}
catch (ClassNotFoundException ecn)
{
ecn.printStackTrace();
}
}
});
f.pack();
f.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}
Result on application start.
Result after button "Run" pressed.
Every thing is right in the given program but connection to database is not established.
What could be the possible reason?Is it driver related problem. I want to do this without DSN.
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class FormAccess1 extends Frame implements ActionListener {
private static ResultSet rs;
Panel p1;
TextField t1, t2;
Button next;
public FormAccess1() {
super("Applicant Detail");
setLayout(new GridLayout(5, 1));
p1 = new Panel();
t1 = new TextField(10);
t2 = new TextField(10);
add(p1);
next = new Button("Next");
p1.add(new Label("book-id"));
p1.add(t1);
p1.add(new Label("book-title"));
p1.add(t2);
p1.add(next);
next.addActionListener(this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == next) {
try {
rs.next();
} catch (Exception em) {
}
showRecord(rs);
}
}
public void showRecord(ResultSet rs) {
try {
t1.setText(rs.getString(1));
t2.setText(rs.getString(2));
} catch (Exception ex) {
}
}
public static void main(String arg[]) {
FormAccess1 app = new FormAccess1();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.accdb)};DBQ=MyDatabase.accdb;DriverID=01";
Connection con = DriverManager.getConnection(database, "", "");
Statement state = con.createStatement();
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
rs.next();
app.showRecord(rs);
} catch (Exception ey) {
}
}
}
Verify you have de correct access drivers in the machine (Access 2013 redistributables). It could be x86 or x64. Jre/Jdk should be in concordance: x86 or x64