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
Related
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.
I'm facing a problem in this program there are two GUI's.When user click on button it checks for a database connection when connection become successful then second GUI appear which has JComboBox. But the problem is it doesn't show the catalogs of mysql in JComboBox.
Main Method:
public class Main {
public static void main(String[] args) {
Gui obj = new Gui();
}
}
First Gui
public class Gui extends JFrame {
Connector c = new Connector();
private JButton b1;
public Gui() {
b1 = new JButton("Click To Connect");
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (c.getConnect() == true) {
dispose();
new Gui2();
}
}
});
add(b1);
setLayout(new FlowLayout());
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Connection Class
public class Connector {
private Connection conn;
public boolean getConnect() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "john", "root");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
if (conn == null) {
System.out.println("Connection Failed");
return false;
}
System.out.println("Connection Success");
return true;
}
}
ComboBox GUI
public class Gui2 extends JFrame {
private JComboBox box;
Connection connection;
public Gui2() {
box = new JComboBox();
opencatalog();
add(box);
setLayout(new FlowLayout());
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private void opencatalog() {
try {
DatabaseMetaData meta = connection.getMetaData();
ResultSet rs = meta.getCatalogs();
List ct = new ArrayList();
while (rs.next()) {
ct.add(rs.getString(1));
}
rs.close();
box.setModel(new DefaultComboBoxModel(ct.toArray()));
box.setSelectedItem(connection.getCatalog());
box.setEnabled(ct.size() > 0);
}
catch (Exception e) {
System.out.println(e.toString());
}
box.setEnabled(false);
}
}
Connector class
change the return type to Connection and return conn.
public Connection getConnect() {
....
return conn
}
Gui class, change the condition
public void actionPerformed(ActionEvent arg0) {
Connection conn= c.getConnect();
if (conn!=null) {
new Gui2(conn);//pass connection object here
dispose();
}
}
Gui2 class, constructor should be
public Gui2(Connection conn)
{
connection=conn;
box = new JComboBox();
.................
}
Gui2 class,
box.setEnabled(true);//should be enabled,
I am using a JTable to display data from my database. What I want to happen is that when a row is clicked it opens another window.
My Code
Connection to the database
public class JFrametest extends javax.swing.JFrame {
private static Connection connection;
private static Statement stmt;
static {
// standard code to open a connection and statement to Java Derby database
try {
NetworkServerControl server = new NetworkServerControl();
server.start(null);
// Load JDBC driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Establish a connection
String sourceURL = "jdbc:derby://localhost:1527/"
+ new File("EmailsDB").getAbsolutePath() + ";";
connection = DriverManager.getConnection(sourceURL, "student", "student");
stmt = connection.createStatement();
} // The following exceptions must be caught
catch (ClassNotFoundException cnfe) {
out.println(cnfe);
} catch (SQLException sqle) {
out.println(sqle);
} catch (Exception e) {
System.out.println(e);
}
}
Displaying Data from the database
try {
String query = "select * from messages";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e) {
e.printStackTrace();
}
As anyone got any ideas on what i can do? is this possible?
You could use a mouseClicked Action Listener to do this.
You can use MouseListener for that, here is simple example:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TestFrame extends JFrame {
public static void main(String... s) {
new TestFrame();
}
private JTable t;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
DefaultTableModel model = new DefaultTableModel(0,2);
for(int i=0;i<10;i++){
model.addRow(new Object[]{i,"other info "+i});
}
model.setColumnIdentifiers(new Object[]{"id","info"});
t = new JTable(model);
t.addMouseListener(getListener());
add(new JScrollPane(t));
}
protected void showDialog(int rowAtPoint) {
Object valueAt = t.getValueAt(rowAtPoint, 0);
// other operations
JDialog d = new JDialog();
d.setTitle("id="+valueAt);
d.setModal(true);
d.setAlwaysOnTop(true);
d.setLocationRelativeTo(null);
d.pack();
d.setVisible(true);
}
private MouseListener getListener() {
return new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(e.getClickCount() >= 1){
int rowAtPoint = t.rowAtPoint(e.getPoint());
if(rowAtPoint != -1)
showDialog(rowAtPoint);
}
}
};
}
}
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.)