Unable to resolve NullPointerException in java swing application - java

I made a simple login page with Java Swing in Eclipse and once I run and enter the inputs I am getting an error java.lang.NullPointerException
import java.lang.String;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class trail extends JFrame {
Connection connection =null;
private JPanel contentPane;
private JTextField id;
private JPasswordField passwordField;
public static void main(String[] args) {
String jdbcURL = "jdbc:postgresql://localhost:5432/postgres";
String username = "postgres";
String password = ".......";
try {
Connection connection = DriverManager.getConnection(jdbcURL, username, password);
System.out.print("Connected");
connection.close();
}
catch(SQLException e) {
System.out.println("Error in connection");
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
trail frame = new trail();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public trail() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 519, 550);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("username");
lblNewLabel.setBounds(94, 114, 45, 13);
contentPane.add(lblNewLabel);
id = new JTextField();
id.setBounds(246, 111, 96, 19);
contentPane.add(id);
id.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("password");
lblNewLabel_1.setBounds(94, 178, 45, 13);
contentPane.add(lblNewLabel_1);
passwordField = new JPasswordField();
passwordField.setBounds(246, 175, 96, 19);
contentPane.add(passwordField);
JButton btnlogin = new JButton("login");
btnlogin.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
try {
String query = "select * from users where username = ? and password = ?";
PreparedStatement pst=connection.prepareStatement(query);
pst.setString(1, id.getText());
pst.setString(2, passwordField.getText());
ResultSet rs = pst.executeQuery();
int count = 0;
while(rs.next()) {
count = count + 1;
if(count == 1)
{
JOptionPane.showMessageDialog(null, "Password and username is correct");
}
else if(count>1)
{
JOptionPane.showMessageDialog(null, "redundancy detected");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect credentials");
}
}
rs.close();
pst.close();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, e1);
}
}
});
btnlogin.setBounds(179, 259, 85, 21);
contentPane.add(btnlogin);
}
}

You have declared Connection connection =null; later on in the try block you are using like
Connection connection = DriverManager.getConnection(jdbcURL, username, password) which is altogether different Connection object. you should be using something like .
this.connection=DriverManager.getConnection(jdbcURL, username, password)
Also you can move your code in a different method like
public void initialize() {
String jdbcURL = "jdbc:postgresql://localhost:5432/your_db";
String username = "postgres";
String password = "password";
try {
this.connection = DriverManager.getConnection(jdbcURL, username, password);
System.out.print("Connected");
connection.close();
}
catch(SQLException e) {
System.out.println("Error in connection");
e.printStackTrace();
}
}
And call inside the constructor like
public trail() {
initialize();
....
}

Related

How do make a login function using BufferedReader?

I am a first-year programming student and I was tasked to make a Login and Register program using Java Swing (Application Window) and BufferedReader+Writer. I am now able to write a username and password into a text file via BWriter, however I have no idea how to make the Login read the text file and only Login when the inputted username and password in their respected TextField matches the one I wrote into the text file. (For reference the text file looks like this after I wrote the supposed username and password from the Register portion: Redman, 1234)
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.awt.event.ActionEvent;
public class Register {
private JFrame frame;
private JTextField tfNewUser;
private JTextField tfNewPass;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Register window = new Register();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Register() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setTitle("Register");
frame.setBounds(100, 100, 286, 324);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("REGISTER ");
lblNewLabel.setBounds(10, 11, 250, 26);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 12));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(lblNewLabel);
tfNewUser = new JTextField();
tfNewUser.setBounds(117, 48, 143, 20);
frame.getContentPane().add(tfNewUser);
tfNewUser.setColumns(10);
tfNewPass = new JTextField();
tfNewPass.setBounds(117, 79, 143, 20);
tfNewPass.setColumns(10);
frame.getContentPane().add(tfNewPass);
JButton btnReg = new JButton("REGISTER");
btnReg.setBounds(10, 110, 250, 23);
btnReg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String regUser = tfNewUser.getText().toString();
String regPass = tfNewPass.getText().toString();
addReg(regUser, regPass);
}
});
frame.getContentPane().add(btnReg);
JButton btnUpdate = new JButton("UPDATE CREDENTIALS");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpdateCreds newformu = new UpdateCreds();
newformu.main(null);
frame.setVisible(false);
}
});
btnUpdate.setBounds(10, 213, 250, 23);
frame.getContentPane().add(btnUpdate);
JButton btnReturn = new JButton("RETURN TO LOGIN");
btnReturn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Login newform = new Login();
newform.main(null);
frame.setVisible(false);
}
});
btnReturn.setBounds(10, 142, 250, 23);
frame.getContentPane().add(btnReturn);
JLabel lblNewLabel_1 = new JLabel("New Username: ");
lblNewLabel_1.setBounds(10, 48, 97, 14);
frame.getContentPane().add(lblNewLabel_1);
JLabel lblNewLabel_1_1 = new JLabel("New Password: ");
lblNewLabel_1_1.setBounds(10, 82, 97, 14);
frame.getContentPane().add(lblNewLabel_1_1);
JButton btnDeleteAcc = new JButton("DELETE ACCOUNT");
btnDeleteAcc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteAcc();
}
});
btnDeleteAcc.setBounds(10, 247, 250, 23);
frame.getContentPane().add(btnDeleteAcc);
JLabel lblAccountSettings = new JLabel("ACCOUNT SETTINGS");
lblAccountSettings.setBounds(10, 176, 250, 26);
lblAccountSettings.setHorizontalAlignment(SwingConstants.CENTER);
lblAccountSettings.setFont(new Font("Tahoma", Font.BOLD, 12));
frame.getContentPane().add(lblAccountSettings);
}
public void errorPane (String msg, String status) {
JOptionPane.showMessageDialog(frame, msg, status, JOptionPane.ERROR_MESSAGE);
}
public void succMess (String smsg, String status2) {
JOptionPane.showMessageDialog(frame, smsg, status2, JOptionPane.INFORMATION_MESSAGE);
}
public void clearTF() {
tfNewUser.setText("");
tfNewPass.setText("");
}
public void addReg(String regUser, String regPass) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("Creds", true));
bw.write(regUser+", "+regPass);
bw.flush();
bw.newLine();
bw.close();
succMess ("Account registered!", "SUCCESS");
clearTF();
}
catch (Exception e) {
errorPane("There is a problem with the data. Please input new data.", "ERROR" );
}
}
public void deleteAcc() {
try {
String record;
String regUser = tfNewUser.getText().toString();
File tempCred = new File("Creds_temp");
File cred = new File ("Creds");
BufferedReader br = new BufferedReader(new FileReader(cred));
BufferedWriter bw = new BufferedWriter(new FileWriter(tempCred));
while((record = br.readLine())!=null) {
if(record.contains(regUser))
continue;
bw.write(record);
bw.flush();
bw.newLine();
}
br.close();
bw.close();
cred.delete();
tempCred.renameTo(cred);
succMess ("Account Deleted!", "SUCCESS");
}
catch (Exception e) {
errorPane("Cannot find account. Please register an account first.", "ERROR" );
}
}
}
So assuming that the login file only deals with the authentication...
Read the .txt file line by line (I'm using Java Scanner for convenience, but you could use FileReader or anything else as well)
Split each line by comma delimiters and store the data in a hash map
Compare whether the user input matches one
In Login.java:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.HashMap;
public class Login {
private HashMap<String, String> userData = new HashMap<String, String>();
private String name;
private String password;
void readFile() {
try {
// read file
File file = new File("passwords.txt"); // replace with file name!!
Scanner reader = new Scanner(file);
// loop through each line inside the file being read
while (reader.hasNextLine()) {
String str = reader.nextLine();
String[] user = str.split(", "); // user[0] = anything before ", " and user[1] = anything after ", "
userData.put(user[0], user[1]); // store username and password
}
reader.close(); // remember to close the reader
} catch (FileNotFoundException e) {
System.out.println("Something happened...");
e.printStackTrace();
}
}
public boolean loggedIn() {
return password.equals(userData.get(name));
}
// constructor to execute on instance creation
public Login(String name, String password) {
// initialize data
this.name = name;
this.password = password;
readFile();
}
}
And pretend your user data file (passwords.txt) looks something like:
Redman, 1234
Bob, $up3r-$ecur3
Rob, pls don't hack
Using the class is pretty easy:
Login attempt = new Login(username, password); // replace with requested variables as string
boolean success = attempt.loggedIn();
if(success) {
// logged in successfully
} else {
// incorrect username or password!
}
Working (only login) example.
Hope that helps you get somewhere.

Why the preparedStatement is not working in jdbc?

I have created a table called user in mysql. Then I create a simple j frame with having a text field and a button. The button will add the name in the DB after pressing the button. But is showing an error at insertData.InsertData$2.actionPerformed(InsertData.java:86) means there are some issue with prepared statement. I have tried without prepared statement but problem is not solved.
Most important my table having 4 columns called (name, id, Email,Phone)
package insertData;
import java.awt.EventQueue;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JTextField;
import com.mysql.cj.xdevapi.Statement;
import com.sun.jdi.connect.spi.Connection;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class InsertData {
private JFrame frame;
private JTextField textField;
Connection connection;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InsertData window = new InsertData();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public InsertData() {
initialize();
createConnection();
}
/**
* Initialize the contents of the frame.
*/
public void createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");//load driver
java.sql.Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/shykat_db","root","root"); //Establish connection
System.out.println("sucess");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(10, 25, 174, 44);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Submit\r\n");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String name=textField.getText();
String drop="insert into user values(?) ";
java.sql.PreparedStatement ps= ((java.sql.Connection) connection).prepareStatement(drop);
System.out.println(ps);
ps.setString(1, name);
ps.executeUpdate();
//ResultSet rs = ps.executeQuery();
//System.out.println(rs);
//java.sql.Statement stm=((java.sql.Connection) connection).createStatement();
//String drop="insert into user values(' "+name+" ')";
//stm.execute(drop);
//stm.close();
//int count=ps.executeUpdate();
//System.out.println(count+"-----Data updated");
ps.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(313, 26, 89, 44);
frame.getContentPane().add(btnNewButton);
}
}
If you want to insert into only some columns of a multi column table, you must declare which columns you want to insert into after the table name
INSERT INTO t(column,list,goes,here)
VALUES(samenumber,ofvalues,asthere,arecolumns)
Your user table has at least 4 columns, you cannot say insert into user values(?) because your database will not be prepared to guess which column the value should go in. Try insert into user(name) values(?)

SQLIntegrityConstraintViolationException,

Im trying to create a basic program where i can add and delete data within Java Derby database. However the problem is that it throws an exception with 'The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL160724181654400' defined on 'CONTACTS_LIST'. ' The main objective is to add strings of text within 2 JTextFields and import that into my database which has only 2 colums. I do not understand where the problem is though.
try {
String writeString = "INSERT INTO Contacts_List(NAME, NUMBER) VALUES(?,?)";
PreparedStatement pst = connection.prepareStatement(writeString);
pst.setString(1, nameF.getText());
pst.setString(2, numberL.getText());
pst.execute();
showMessageDialog(this, " Contact's added! ");
nameF.setText(" ");
numberF.setText(" ");
pst.close();
} catch (Exception ex) {
ex.printStackTrace();
}
and my full code is below;
package address_book;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.showMessageDialog;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.apache.derby.drda.NetworkServerControl;
public class Add_Data extends JFrame implements ActionListener {
JButton add = new JButton("Add To database");
JTextField nameF = new JTextField(12);
JTextField numberF = new JTextField(12);
JLabel nameL = new JLabel("Enter Name : ");
JLabel numberL = new JLabel("Enter Number : ");
private static Connection connection;
private static Statement stmt;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Add_Data().setVisible(true);
}
});
}
public Add_Data() {
super("Add Contact");
setSize(300, 250);
setVisible(true);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// add jpanel and the layout
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(10, 10, 10, 10);
// add componenets
constraints.gridx = 0;
constraints.gridy = 0;
panel.add(nameL, constraints);
constraints.gridx = 1;
panel.add(nameF, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
panel.add(numberL, constraints);
constraints.gridx = 1;
panel.add(numberF, constraints);
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 2;
constraints.anchor = GridBagConstraints.CENTER;
panel.add(add, constraints);
add.addActionListener(this);
//create border
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Enter Contact's Details"));
add(panel);
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("Contacts_List").getAbsolutePath() + ";";
connection = DriverManager.getConnection(sourceURL, "use", "use");
stmt = connection.createStatement();
} // The following exceptions must be caught
catch (ClassNotFoundException cnfe) {
System.out.println(cnfe);
} catch (SQLException sqle) {
System.out.println(sqle);
} catch (Exception e) {
System.out.println(e);
}
}
#Override
public void actionPerformed(ActionEvent e) {
String key = nameF.getText();
String name = Database.getName(key);
String nameAdd = nameF.getText();
if (nameF.getText().isEmpty() || numberF.getText().isEmpty() && e.getSource() == add) {
JOptionPane.showMessageDialog(this, "Fill the empty fields");
} else if (e.getSource() == add) {
if (name == null) {
int confirm = JOptionPane.showConfirmDialog(null, "You are about to add " + nameAdd + ", Do you want to Continue?");
if (confirm == JOptionPane.YES_OPTION) {
try {
String writeString = "INSERT INTO Contacts_List(NAME, NUMBER) VALUES(?,?)";
PreparedStatement pst = connection.prepareStatement(writeString);
pst.setString(1, nameF.getText());
pst.setString(2, numberL.getText());
pst.execute();
showMessageDialog(this, " Contact's added! ");
nameF.setText(" ");
numberF.setText(" ");
pst.close();
} catch (Exception ex) {
ex.printStackTrace();
}
if (confirm == JOptionPane.NO_OPTION) {
showMessageDialog(this, "Please Try Again !");
}
}
}
}
}
}

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.

Categories