cannot insert values in my MS access using java - java

i am creating a shipping agency application that's supposed to add new companies, (insert) data, modify existing companies(modify) and delete companies from the database but unfortunately i am unable to do all that. however i was able to link the whole application to my existing MS Access database.
PLEASE HELP, I appreciated your quick responses on my previous query.
import java.awt.Container;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
//
//
//
//
// Generated by StarUML(tm) Java Add-In
//
// # Project : Untitled
// # File Name : Companies.java
// # Date : 3/22/2018
// # Author : izukanji Simumba
//
//
public class Company extends System {
public static JFrame Cframe = new JFrame("Companies");
public static JLabel ca = new JLabel(" Record Name :");
public static JLabel cb= new JLabel(" Address :");
public static JLabel cc = new JLabel(" Mailing List :");
public static JLabel cd = new JLabel(" Location :");
public static JLabel ce = new JLabel(" Cost :");
public static JTextField txtca = new JTextField(10);
public static JTextField txtcb = new JTextField(10);
public static JTextField txtcc = new JTextField(10);
public static JTextField txtcd = new JTextField(10);
public static JTextField txtce = new JTextField(10);
public static JButton btnadd1 = new JButton(" add ");
public static JButton btnadd2 = new JButton(" modify ");
public static JButton btnadd3 = new JButton(" delete ");
public static void connect(){
Connection conn = null;
try {
//db parameters
String path = "jdbc:ucanaccess://C:/sqlite/db1.accdb";
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
conn = DriverManager.getConnection(path);
JOptionPane.showMessageDialog(null, "Connection to Sqlite has been established");
} catch (SQLException | ClassNotFoundException e) {
java.lang.System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex){
java.lang.System.out.println(ex.getMessage());
} }
}
public Company() {
JPanel Companypanel = new JPanel();
Cframe.setSize(620,365);
Cframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Cframe.setVisible(true);
Cframe.setBackground(Color.PINK);
JPanel Cpanel = new JPanel();
Cpanel.setBackground(new Color(238, 232, 170));
Cpanel.setLayout(null);
ca.setBounds(30, 51, 115, 14);
Cpanel.add(ca);
txtca.setBounds(155, 48, 86, 20);
Cpanel.add(txtca);
cb.setBounds(30, 95, 115, 14);
Cpanel.add(cb);
txtcb.setBounds(155, 92, 86, 20);
Cpanel.add(txtcb);
cc.setBounds(335, 51, 112, 14);
Cpanel.add(cc);
txtcc.setBounds(457, 48, 86, 20);
Cpanel.add(txtcc);
cd.setBounds(335, 95, 112, 14);
Cpanel.add(cd);
txtcd.setBounds(457, 92, 86, 20);
Cpanel.add(txtcd);
ce.setBounds(335, 146, 112, 14);
Cpanel.add(ce);
txtce.setBounds(457, 143, 86, 20);
Cpanel.add(txtce);
btnadd1.setBounds(67, 217, 95, 23);
Cpanel.add(btnadd1);
btnadd2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String path = "UPDATE Companies Set NAME = ? , "
+ " ADDRESS= ? "
+ " LOCATION= ? "
+ " COST= ? "
+ "WHERE MAILINGLIST = ?";
pst = conn.prepareStatement(path);
pst.setString(1, txtca.getText());
pst.setString(2, txtcb.getText());
pst.setString(3, txtcc.getText());
pst.setString(4, txtcd.getText());
pst.setString(5, txtce.getText());
pst.executeUpdate(path);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
});
btnadd2.setBounds(214, 217, 115, 23);
Cpanel.add(btnadd2);
btnadd3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String path = "DELETE From COMPANY Set NAME = ? , "
+ " ADDRESS= ? "
+ " LOCATION= ? "
+ " COST= ? "
+ "WHERE MAILINGLIST = ?";
pst = conn.prepareStatement(path);
pst.setString(1, txtca.getText());
pst.setString(2, txtcb.getText());
pst.setString(3, txtcc.getText());
pst.setString(4, txtcd.getText());
pst.setString(5, txtce.getText());
pst.executeUpdate(path);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
});
btnadd3.setBounds(391, 217, 95, 23);
Cpanel.add(btnadd3);
Cframe.getContentPane().add(Cpanel);
btnAction();
btnadd1.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e){
try {
String path="insert into Companies(MAILINGLIST, NAME, LOCATION, ADDRESS, COST) values (?,?,?,?,?)";
pst = conn.prepareStatement(path);
pst.setString(1, txtca.getText());
pst.setString(2, txtcb.getText());
pst.setString(3, txtcc.getText());
pst.setString(4, txtcd.getText());
pst.setString(5, txtce.getText());
pst.executeUpdate(path);
JOptionPane.showMessageDialog(null, "New Company Added");
rs.close();
pst.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
new Company();
Cframe.dispose();
}
});
}
private void btnAction() {
// TODO Auto-generated method stub
}
private String RecordName;
private String Address;
private String Location;
private Integer Cost;
private String MailingList;
public void getRecordName() {
}
public void setRecordName(String crname) {
}
public void getAddress() {
}
public void setAddress(String caddress) {
}
public void getLocation() {
}
public void setLocation(String clocation) {
}
public void getCost() {
}
public void setCost(Integer ccost) {
}
public void getMailingList() {
}
public void setMailingList(String cmailinglist) {
}
}

Related

My project runs and connect to database (access .mbd) in net beans but jar does not connect to database, keep saying invalid USER OR PASSWORD

I have made a program which takes (username and password) as input and check it with the username and password stored in database (student.mbd).
This works fine and have no issue but, when i try to run jar file throws exception and says Invalid username or password.
the login page code is :
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Login extends JFrame implements ActionListener {
Container c = getContentPane();
private JButton btnLogin, btnCancel;
private JLabel lblUName, lblPasswd;
private JTextField txtUName;
private JPasswordField txtPasswd;
public Login() {
super("Login ...");
this.setSize(350, 200);
this.setLayout(null);
this.setResizable(false);
this.setLocation((Settings.getScreenSize().width / 2) - 175, (Settings.getScreenSize().height / 2) - 150);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
lblUName = new JLabel("Username");
lblPasswd = new JLabel("Password");
txtUName = new JTextField();
txtPasswd = new JPasswordField();
btnLogin = new JButton("Login");
btnCancel = new JButton("Cancel");
lblUName.setBounds(50, 40, 140, 25);
txtUName.setBounds(150, 40, 130, 25);
lblPasswd.setBounds(50, 80, 140, 25);
txtPasswd.setBounds(150, 80, 130, 25);
btnLogin.setBounds(50, 120, 100, 25);
btnCancel.setBounds(180, 120, 100, 25);
btnLogin.addActionListener(this);
btnCancel.addActionListener(this);
this.add(lblUName);
this.add(lblPasswd);
this.add(txtUName);
this.add(txtPasswd);
this.add(btnLogin);
this.add(btnCancel);
}//constructor closed
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnLogin) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:student");
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM UAD WHERE Username='" + txtUName.getText() +
"' and Password='" + txtPasswd.getText() + "'");
if (rs.next()) {
if (rs.getString(3).equals("Student")) {
userMDI frm = new userMDI();
frm.setVisible(true);
} else {
new frmAdminMDI().setVisible(true);
}
this.dispose();
}else{
JOptionPane.showMessageDialog(null,"Invalid username or password","Invalid",JOptionPane.ERROR_MESSAGE);
}
con.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Invalid username or password", "Invalid", JOptionPane.ERROR_MESSAGE);
txtUName.setText("");
txtPasswd.setText("");
}//inner try catch closed
} catch (Exception x) {
JOptionPane.showMessageDialog(null, "Unable to connect to the database", "Connection error", JOptionPane.ERROR_MESSAGE);
}//outer try catch closed
}//if closed
if (e.getSource() == btnCancel) {
System.exit(0);
}//if closed
}//actionPerformed() closed
public static void main(String args[]) {
new Login().setVisible(true);
}
}//class closed
please help me, as i have to submit jar file and submit it as college project..
to download the whole project http://www.4shared.com/rar/9sz2jBtE/CollegeInformationSystem.html
I assume you are getting unhandled exception. Check your DNS setup. Did you try passing username/password in the code?
Connection con = DriverManager.getConnection("jdbc:odbc:student","username","password");

Eclipse Jasper report in Java Swing Application

Good Day, I have created a Java GUI with Eclipse(Java JDK 1.8.0_31 & Eclipse 4.4.1). So then I have installed Jasper report v6 in my same project and created jasper report inside my project.
It is generating report and opening Jasper Viewer window.
See the code below;
DB.java
package jasper1;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class DB {
Connection conn = null;
public static class database {
public static String host;
public static String db;
public static String user;
public static String pwd;
}
public static Connection Connector(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://"+database.host+":3306/" +database.db ,database.user,database.pwd);
return conn;
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Login Failed.\n" + e);
return null;
}
}
}
form1.java
package jasper1;
import jasper1.DB.database;
import java.awt.EventQueue;
import java.sql.Connection;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class form1 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
form1 window = new form1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conn = null;
private JTextField text_Host;
private JTextField text_DB;
private JTextField text_User;
private JTextField text_Pwd;
/**
* Create the application.
*/
public form1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Connect");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
btnNewButton.setText("Please wait...");
}
#Override
public void mouseReleased(MouseEvent e) {
btnNewButton.setText("Connect");
}
});
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
database.host = text_Host.getText();
database.db = text_DB.getText();
database.user = text_User.getText();
database.pwd = text_Pwd.getText();
conn = DB.Connector();
if(conn != null){
//JOptionPane.showMessageDialog(null, "Successfully Connected");
String reportPath = "reports/report.jrxml";
try {
JasperReport jr = JasperCompileManager.compileReport(reportPath);
//JOptionPane.showMessageDialog(null, conn);
JasperPrint jp = JasperFillManager.fillReport(jr, null, conn);
JasperViewer.viewReport(jp);
conn.close();
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
}
return;
}
}
});
btnNewButton.setBounds(73, 167, 130, 23);
frame.getContentPane().add(btnNewButton);
text_Host = new JTextField();
text_Host.setText("localhost");
text_Host.setBounds(93, 32, 110, 20);
frame.getContentPane().add(text_Host);
text_Host.setColumns(10);
text_DB = new JTextField();
text_DB.setText("qatarclean");
text_DB.setBounds(93, 63, 110, 20);
frame.getContentPane().add(text_DB);
text_DB.setColumns(10);
text_User = new JTextField();
text_User.setText("root");
text_User.setBounds(93, 94, 110, 20);
frame.getContentPane().add(text_User);
text_User.setColumns(10);
text_Pwd = new JTextField();
text_Pwd.setText("supun123");
text_Pwd.setBounds(93, 125, 110, 20);
frame.getContentPane().add(text_Pwd);
text_Pwd.setColumns(10);
JLabel lblHost = new JLabel("Host");
lblHost.setBounds(38, 31, 46, 23);
frame.getContentPane().add(lblHost);
JLabel lblDatabase = new JLabel("Database");
lblDatabase.setBounds(38, 63, 56, 20);
frame.getContentPane().add(lblDatabase);
JLabel lblUserName = new JLabel("User Name");
lblUserName.setBounds(38, 94, 67, 23);
frame.getContentPane().add(lblUserName);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(38, 125, 56, 20);
frame.getContentPane().add(lblPassword);
}
}
The questions are:
Is there any way to view this report inside my form object?.
How can I compile this to one file to work in cross platform? I tried to export it to .Jar(Executable Jar) file. But it doesn't include report.jrxml. It is not secure to keep jrxml file outside because it's user readable. How can I compile the project more secure?
What are the exact Jasper Library jar files to add in the project? I have added all jars in jasperreports-6.0.0\dist and jasperreports-6.0.0\lib. When I export it to Executable Jar, file size will be more than 50MB.
If anyone has alternate solution like BIRT Reports, Kindly answer these questions instead of Jasper Reports.

java.sql.SQLException:[SQLITE_ERROR] SQL error or missing database (near “=”:syntax error)

I made the sqlite database using the firefox web development thing, saved it to my pc but I ran into some problem while linking the database. Whenever I click the login button to test I get "java.sql.SQLException:[SQLITE_ERROR] SQL error or missing database (near "=":syntax error)". He advise me to change the "//" to "\" within the database class and see if it worked but it didn't so if someone could look at the code and help me out it would greatly appreciated.
code for loader
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Loader extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JLabel username;
JTextField userField;
JButton register;
JLabel password;
JPasswordField passField;
JButton login;
ImageIcon logo;
JLabel imageLogo;
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
Loader() {
conn = DBConnect.ConnectDB();
setLayout(null);
username = new JLabel("Username");
username.setBounds(100, 75, 75, 75);
userField = new JTextField("", 10);
userField.setBounds(162, 102, 90, 20);
register = new JButton("Register");
register.setForeground(Color.white);
register.setBackground(Color.black);
register.setBounds(275, 95, 90, 30);
password = new JLabel("Password");
password.setBounds(100, 105, 75, 75);
passField = new JPasswordField();
passField.setBounds(162, 132, 90, 20);
login = new JButton("Login");
login.addActionListener(this);
login.setBounds(275, 125, 90, 30);
login.setForeground(Color.white);
login.setBackground(Color.black);
logo = new ImageIcon(getClass().getResource("nameless.png"));
imageLogo = new JLabel(logo);
imageLogo.setBounds(110, 25, 250, 40);
add(username);
add(userField);
add(register);
add(password);
add(passField);
add(login);
add(imageLogo);
}
#Override
public void actionPerformed(ActionEvent e) {
String sql = "SELECT = FROM Users WHERE Username=? AND Password=?";
try{
ps = conn.prepareStatement(sql);
ps.setString(1, userField.getText());
ps.setString(2, passField.getText());
rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Logged In!", "Logged In", JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(null, "Invalid Detail.\nPlease Try Agian.", "Error", JOptionPane.ERROR_MESSAGE);
userField.setText("");
passField.setText("");
}
}catch(Exception a){
JOptionPane.showMessageDialog(null, a);
}
finally {
try{
rs.close();
ps.close();
}catch(Exception a) {
}
}
}
}
main statement
import javax.swing.JFrame;
public class MainStatement {
public static void main(String Args[]) {
Loader l = new Loader();
l.setVisible(true);
l.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l.setResizable(false);
l.setSize(450, 200);
l.setTitle("Nameless™ Database");
}
}
database class
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class DBConnect {
public static Connection ConnectDB(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\YellowMilk\\Folders\\Private\\Java\\NamelessDatabase.sqli​te");
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
"SELECT = FROM Users WHERE Username=? AND Password=?"
The first = is a syntax error. It should be like this
"SELECT 1 FROM Users WHERE Username=? AND Password=?"
Since you don't care about what's in the rows, you just want to count how many rows they are, so you return a dummy number 1 per row returned.
If you want all of the fields of the row then you'd do this:
"SELECT * FROM Users WHERE Username=? AND Password=?"
But = is a syntax error, you can't have = there.

java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver

I have java source,and when I run,it writes
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver
I thinks it is needed ODBC driver,but I can't see it.
Java source code:
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.image.*;
import java.awt.event.*;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class a extends javax.swing.JDialog {
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JLabel jLabel4;
private JTextField txtPiradi;
private JTextField txtSaxeli;
private JTextField txtGvari;
Image img;
File file = null;
String path = "";
JTextField text = new JTextField(20);
JButton browse, save;
Connection conn = null;
ResultSet rs = null;
Statement stmt = null;
/**
* Auto-generated main method to display this JDialog
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
wevrtaDamateba inst = new wevrtaDamateba(frame);
inst.setVisible(true);
}
});
}
public wevrtaDamateba(JFrame frame) {
super(frame);
initGUI();
}
private void initGUI() {
try {
{
getContentPane().setLayout(null);
this.setTitle("\u10d0\u10ee\u10d0\u10da\u10d8 \u10ec\u10d4\u10d5\u10e0\u10d8\u10e1 \u10d3\u10d0\u10db\u10d0\u10e2\u10d4\u10d1\u10d0");
{
jLabel1 = new JLabel();
getContentPane().add(jLabel1);
jLabel1.setText("\u10e1\u10d0\u10ee\u10d4\u10da\u10d8:");
jLabel1.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel1.setBounds(78, 21, 60, 40);
}
{
jLabel2 = new JLabel();
getContentPane().add(jLabel2);
jLabel2.setText("\u10d2\u10d5\u10d0\u10e0\u10d8:");
jLabel2.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel2.setBounds(78, 67, 60, 40);
}
{
jLabel3 = new JLabel();
getContentPane().add(jLabel3);
jLabel3.setText("\u10de\u10d8\u10e0\u10d0\u10d3\u10d8 N:");
jLabel3.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel3.setBounds(78, 112, 60, 40);
}
{
jLabel4 = new JLabel();
getContentPane().add(jLabel4);
jLabel4.setText("\u10e1\u10e3\u10e0\u10d0\u10d7\u10d8:");
jLabel4.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel4.setBounds(78, 152, 60, 40);
}
{
txtSaxeli = new JTextField();
getContentPane().add(txtSaxeli);
txtSaxeli.setBounds(161, 28, 180, 23);
}
{
txtGvari = new JTextField();
getContentPane().add(txtGvari);
txtGvari.setBounds(161, 74, 180, 23);
}
{
txtPiradi = new JTextField();
getContentPane().add(txtPiradi);
txtPiradi.setBounds(161, 119, 180, 23);
}
{
browse = new JButton();
getContentPane().add(browse);
browse.setText("\u10e1\u10e3\u10e0\u10d0\u10d7\u10d8\u10e1 \u10d0\u10e0\u10e9\u10d4\u10d5\u10d0");
browse.setBounds(161, 159, 180, 23);
browse.setFont(new java.awt.Font("Sylfaen",0,12));
browse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.addChoosableFileFilter(new ImageFileFilter());
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
path = file.getPath();
ImageIcon icon = new ImageIcon(path);
// label.setIcon(icon);
text.setText(path);
repaint();
}
}
});
}
{
save = new JButton();
getContentPane().add(save);
save.setText("\u10d3\u10d0\u10db\u10d0\u10e2\u10d4\u10d1\u10d0");
save.setBounds(173, 224, 123, 23);
save.setFont(new java.awt.Font("Sylfaen",0,12));
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
File f = new File(path);
String saxeli = txtSaxeli.getText();
String gvari = txtGvari.getText();
int piradi = Integer.parseInt(txtPiradi.getText());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:Base","","");
PreparedStatement psmnt = conn
.prepareStatement("insert into user('saxeli','gvari','piradi','img') values (?,?,?,?)");
FileInputStream fis = new FileInputStream(f);
psmnt.setString(1, saxeli);
psmnt.setString(2, gvari);
psmnt.setInt(3, piradi);
psmnt.setBinaryStream(4, (InputStream) fis,
(int) (f.length()));
int s = psmnt.executeUpdate();
JOptionPane.showMessageDialog(null,
"Inserted successfully!");
} catch (Exception ex) {
System.out.print(ex);
}
}
});
}
}
this.setSize(665, 346);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void clear() {
// TODO Auto-generated method stub
}
class ImageFileFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
if (file.isDirectory())
return false;
String name = file.getName().toLowerCase();
return (name.endsWith(".jpg") || name.endsWith(".png") || name
.endsWith(".gif"));
}
public String getDescription() {
return "Images (*.gif,*.bmp, *.jpg, *.png )";
}
}
}
Check whether you have Base ODBC DataSource in your ODBC DataSource Panel.

Can´t add data through Java application to database

I have a crazy problem :D I have a Java application with a Jtable and the show, add, delete and update Buttons. The connection to my database works.
Now when I insert Data into my Textfields and click on submit (add) I can see the entry in my Jtable, but I cant see it in my Database.
This is crazy because I already have data in my Database some simple entries and my JTable is showing the data but when I insert data through the java app I can´t see the entry in my phpmyadmin database to which I am connected..
It´s hard to explain but maybe you can find the problem :/
TABLE VIEW FROM JAVA JTABLE http://i.imgur.com/BrRUyx9.jpg
TABLE VIEW FROM PHPMYADMIN.COM http://i.imgur.com/TIbVzmc.jpg
MY CODE
CONTROLLER CLASS
public void controllActionListenerAddEquipmentSubmitBtn(){
main.setActionListenerAddEquipmentSubmitBtn(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==main.getButtonAddEquipmentBtn()){
EquipmentDAO edao = new EquipmentDAO();
try {
edao.create(main.addEquipmentSubmit());
} catch (SQLException e) {
e.printStackTrace();
}
}
}
});
}
MAINFRAME CLASS...(MAIN)
public Equipment addEquipmentSubmit(){
equipment = new Equipment();
equipment.setName(addEquipment.getName());
equipment.setSection(addEquipment.getSection());
equipment.setType(addEquipment.getType());
equipment.setValue(Double.parseDouble((addEquipment.getValue())));
equipment.setAmount(Integer.parseInt(addEquipment.getAmount()));
return equipment;
}
DAOCLASS
package DAOCollection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import com.mysql.jdbc.PreparedStatement;
import notesDBMySQL.DatabaseHandler;
import EntityClasses.Equipment;
public class EquipmentDAO implements DaoInterface{
private Connection con;
private java.sql.PreparedStatement sta;
private Statement std;
private ResultSet res;
private DatabaseHandler handle;
private String query;
#Override
public ResultSet show() throws SQLException{
handle = new DatabaseHandler();
Connection con = handle.buildConnectionToServer();
String query = "select EID as ID, EquipmentName as Name, EquipmentSection as Section, EquipmentType as Type, EquipmentValue as Value, EquipmentAmount as Amount from Equipment";
sta = con.prepareStatement(query);
res = sta.executeQuery(query);
return res;
}
#Override
public void create(Object c) throws SQLException {
handle = new DatabaseHandler();
con = handle.buildConnectionToServer();
std = con.createStatement();
Equipment equ = (Equipment) c ;
query = "INSERT INTO Equipment(EquipmentName,EquipmentSection,EquipmentType,EquipmentValue, EquipmentAmount)"+"VALUES('"+equ.getName()+"','"+equ.getSection()+"','"+equ.getType()+"','"+equ.getValue()+"','"+equ.getAmount()+"')";
std.execute(query);
con.commit();
handle.closeConnection();
}
#Override
public void update(Object c) throws SQLException {
Equipment equ = (Equipment) c;
handle = new DatabaseHandler();
con = handle.buildConnectionToServer();
query = "UPDATE Equipment SET name=?,section=?,type=?,value=?,amount=?,"+"WHERE EID=?";
sta = con.prepareStatement(query);
sta.setString(1, equ.getName());
sta.setString(2,equ.getSection());
sta.setString(3, equ.getType());
sta.setDouble(4, equ.getValue());
sta.setInt(5, equ.getAmount());
sta.setInt(6, equ.getEid());
sta.executeUpdate();
sta.close();
con.close();
handle.closeConnection();
}
#Override
public void delete(int id) throws SQLException {
handle = new DatabaseHandler();
con = handle.buildConnectionToServer();
query = "DELETE FROM EQUIPMENT"+"WHERE EID="+id;
sta.executeUpdate(query);
sta.close();
con.close();
handle.closeConnection();
}
}
ENTITY CLASS
package EntityClasses;
public class Equipment {
private int eid;
private String name;
private String section;
private String type;
private double value;
private int amount;
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
ADD CLASS
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddEquipment extends JPanel {
private JTextField txtu2;
private JTextField txtu3;
private JTextField txtu4;
private JTextField txtu5;
private JTextField txtu6;
private JButton btnu8;
private JButton btnu9; //Back Button
public AddEquipment() {
setLayout(null);
JLabel lblu8 = new JLabel("Add Equipment");
lblu8.setForeground(Color.WHITE);
lblu8.setFont(new Font("Tahoma", Font.BOLD, 16));
lblu8.setBounds(12, 13, 319, 33);
add(lblu8);
JLabel lblu3 = new JLabel("Name");
lblu3.setFont(new Font("Tahoma", Font.BOLD, 13));
lblu3.setBounds(60, 91, 46, 14);
add(lblu3);
txtu2 = new JTextField();
txtu2.setColumns(10);
txtu2.setBounds(221, 88, 377, 22);
add(txtu2);
JLabel lblu4 = new JLabel("Section");
lblu4.setFont(new Font("Tahoma", Font.BOLD, 13));
lblu4.setBounds(60, 156, 69, 14);
add(lblu4);
txtu3 = new JTextField();
txtu3.setColumns(10);
txtu3.setBounds(221, 153, 377, 22);
add(txtu3);
JLabel lblu5 = new JLabel("Type");
lblu5.setFont(new Font("Tahoma", Font.BOLD, 13));
lblu5.setBounds(60, 221, 46, 14);
add(lblu5);
txtu4 = new JTextField();
txtu4.setColumns(10);
txtu4.setBounds(221, 218, 377, 22);
add(txtu4);
JLabel lblu6 = new JLabel("Value");
lblu6.setFont(new Font("Tahoma", Font.BOLD, 13));
lblu6.setBounds(60, 286, 46, 14);
add(lblu6);
txtu5 = new JTextField();
txtu5.setColumns(10);
txtu5.setBounds(221, 283, 377, 22);
add(txtu5);
JLabel lblu7 = new JLabel("Amount");
lblu7.setFont(new Font("Tahoma", Font.BOLD, 13));
lblu7.setBounds(60, 351, 69, 14);
add(lblu7);
txtu6 = new JTextField();
txtu6.setColumns(10);
txtu6.setBounds(221, 348, 377, 22);
add(txtu6);
btnu8 = new JButton("Submit");
btnu8.setFont(new Font("Tahoma", Font.PLAIN, 13));
//btnu8.setBackground(Color.BLACK); // button color
//btnu8.setBackground( new Color(0, 0, 0, 50) ); //opacity
btnu8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnu8.setBounds(422, 534, 110, 30);
add(btnu8);
btnu9 = new JButton("Back");
btnu9.setFont(new Font("Tahoma", Font.PLAIN, 13));
btnu9.setBounds(542, 534, 110, 30);
add(btnu9);
JLabel lblback3 = new JLabel("");
lblback3.setIcon(new ImageIcon("\\\\I-INTRA-03\\IIS-Lehre\\DAPRO-WF4.informatik.hs-ulm.de\\15\\group_together\\GUI_graphics\\background_panel.jpg"));
lblback3.setBounds(0, 0, 664, 577);
add(lblback3);
}
//Getter-Method for the Back Button "btnu9"
public JButton getBackAddEquipment(){
return btnu9;
}
//Getter-Method for the "Submit" Button "btnu8"
public JButton getAddEquipmentBtn(){
return btnu8;
}
public String getName() {
return this.txtu2.getText();
}
// method sets the string value of the textfield
public void setName(String txtu2) {
this.txtu2.setText(txtu2);
}
public String getSection() {
return this.txtu3.getText();
}
public void setSection(String txtu3) {
this.txtu3.setText(txtu3);
}
public String getType() {
return this.txtu4.getText();
}
public void setType(String txtu4) {
this.txtu4.setText(txtu4);
}
public String getValue() {
return this.txtu5.getText();
}
public void setValue(String txtu5) {
this.txtu5.setText(txtu5);
}
public String getAmount() {
return this.txtu6.getText();
}
public void setAmount(String txtu6) {
this.txtu6.setText(txtu6);
}
}
Your DAO implementation is asking for trouble. You should never, ever return a ResultSet. A better idea is to load the data into an object or data structure and close the ResultSet in method scope in a finally block. Same for all your database resources.

Resources