Java JDBC Log in Form - java

I can't seem to get the password and user name on my Java JTextfield and Passwordfield, what I was trying to do is compare user input and check them if the username and password is stored in the database, if so they will be logged in, but the problem is my getText() on my password field is deprecated how would I fix this??
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.JOptionPane;
public class Login extends JFrame {
private JLabel nameLabel;
private JLabel passwordLabel;
private JTextField nameText;
private JPasswordField passwordField;
private JButton submitButton;
Connection conn = null;
public Login(){
super("Log in!");
setLayout(new FlowLayout());
setVisible(true);
setSize(178,190);
setDefaultCloseOperation(EXIT_ON_CLOSE);
nameLabel = new JLabel("User ID: ");
add(nameLabel);
nameText = new JTextField(10);
add(nameText);
passwordLabel = new JLabel("Password: ");
add(passwordLabel);
passwordField = new JPasswordField(10);
add(passwordField);
submitButton = new JButton("Submit");
add(submitButton);
ButtonHandler handler = new ButtonHandler();
submitButton.addActionListener(handler);
}
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
String user = nameText.getText();
String pass = passwordField.getText();
try{
Jdbc test = new Jdbc();
conn = test.dbConn();
String query = "SELECT employee_ID,employee_password FROM user where ='"+user+"'";
}catch(Exception eee){
eee.printStackTrace();
}
}
}
}

Use getPassword() instead of getText() method.
char []passChars=passwordField.getPassword();
if(passChars!=null) {
String pass=new String(passChars);
String sql="SELECT employee_ID,employee_password FROM user
where user=? and employee_password=?";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,user);
ps.setString(2,pass);
ResultSet rs=ps.executeQuery();
if(rs.next()) {
//found
}
else{
//not found
}
rs.close();
ps.close();
conn.close();
}
One thing worth noting is that don't use hard-coded sql statement. Use PreparedStatement to escape string to prevent SQL injection.

char[] p = passField.getPassword();
String password = new String(p);
I think you should use PreparedStatement
PreparedStatement prepstmt = con
.prepareStatement("SELECT employee_ID,employee_password FROM user where username = ? AND Password = ? ");
prepstmt.setString(1, user);
prepstmt.setString(2, password);
ResultSet rs;
rs = prepstmt.executeQuery();
boolean found = rs.next();
if (found)
System.out.println(rs.getString(1));
prepstmt.close();
}

Swing's JPasswordField has the getPassword() method that returns a char array.
String passText = new String(passField.getPassword());

Related

Hopefully a simple fix with connecting to mysql database in java

first and foremost I want to point out I'm a novice programmer without much experience, so excuse me if this question seems obvious to some. Also, since I am not sure what the problem is, I will try to give as much information as possible so sorry I seem to ramble. Anyway what I am trying to do is create a java application with a Jframe, and have it interact with a database. I don't really have any experience with databases or mysql, but I was able to follow along a youtube video, and created a java project which successfully connects to a database, creates a table, and inserts information into that table. I figured I would be able to use the same connection function in my project with my frame.
However when I tried this,the program does not connect or display anything in the console, just simply launches my jframe. Its as if the connection part isn't even there? Connection function I used is :
public static Connection getConnection() throws Exception{
try {String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("connected");
return conn;
}catch(Exception e){System.out.println(e);}
return null;
}
here is my full code, sorry if it is hard to read, I did most of my initial coding in eclipse's window builder. The functions to get a connection and to post to the DB are at the bottom after the main (had them before the main but moved them hoping it would make a difference) any and all help is appreciated !
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import com.toedter.calendar.JDateChooser;
public class TemplatePractice extends JFrame {
private JTextField HTHoursWorked;
private JTextField HTHourlyRate;
private JTextField HTCCTips;
private JTextField PCHours;
private JTextField PCTotal;
private JTextField DisplayTP;
private JTextField DispGPPP;
private JTextField DispBnqtPay;
private JTextField DispEstPay;
JTextField DispActualPC;
private final Action action = new SwingAction();
private TemplatePractice() {
final JTextField PCTotal;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(3, 1, 0, 0));
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel lblNewLabel_1 = new JLabel("Date Worked");
panel.add(lblNewLabel_1);
JDateChooser PCDateWorked = new JDateChooser();
panel.add(PCDateWorked);
JLabel lblHoursWorked = new JLabel("Hours Worked:");
panel.add(lblHoursWorked);
HTHoursWorked = new JTextField();
panel.add(HTHoursWorked);
HTHoursWorked.setColumns(10);
JRadioButton rdbtnRestaruant = new JRadioButton("Restaruant:");
panel.add(rdbtnRestaruant);
JRadioButton rdbtnBanquet = new JRadioButton("Banquet");
panel.add(rdbtnBanquet);
JLabel lblHoursWorked_1 = new JLabel("Hourly Rate: $");
panel.add(lblHoursWorked_1);
HTHourlyRate = new JTextField();
panel.add(HTHourlyRate);
HTHourlyRate.setColumns(10);
JLabel lblCreditCardTips = new JLabel("Credit Card Tips:");
panel.add(lblCreditCardTips);
HTCCTips = new JTextField();
panel.add(HTCCTips);
HTCCTips.setColumns(10);
JButton HTAddBtn = new JButton("Add");
panel.add(HTAddBtn);
JLabel label = new JLabel("");
panel.add(label);
JLabel label_1 = new JLabel("");
panel.add(label_1);
JPanel PCPanel = new JPanel();
getContentPane().add(PCPanel);
JLabel lblPayPeriodStart = new JLabel("Pay Period Start:");
PCPanel.add(lblPayPeriodStart);
JDateChooser PCStartDate = new JDateChooser();
PCPanel.add(PCStartDate);
JLabel lblPayPeriodEnd = new JLabel("Pay Period End");
PCPanel.add(lblPayPeriodEnd);
JDateChooser dateChooser_2 = new JDateChooser();
PCPanel.add(dateChooser_2);
JLabel lblTotalHours = new JLabel("Total Hours:");
PCPanel.add(lblTotalHours);
PCHours = new JTextField();
PCPanel.add(PCHours);
PCHours.setColumns(10);
JLabel lblP = new JLabel("Paycheck Amount: $");
PCPanel.add(lblP);
PCTotal = new JTextField();
PCPanel.add(PCTotal);
PCTotal.setColumns(10);
JButton PCAddBtn = new JButton("Add");
PCAddBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double paydoub = Double.parseDouble(PCTotal.getText());
int i;
for (i=0;i<1000;i++){
double paycheckdouble=0;
paycheckdouble+=paydoub;
double paycheckTotal=paycheckdouble;
String paytotal= String.valueOf(paycheckTotal);
DisplayTP.setText(paytotal);
}
}
});
PCAddBtn.setAction(action);
PCPanel.add(PCAddBtn);
JPanel panel_1 = new JPanel();
getContentPane().add(panel_1);
JButton btnCalculate = new JButton("Calculate");
panel_1.add(btnCalculate);
JLabel lblTotalPay = new JLabel("total pay:");
panel_1.add(lblTotalPay);
DisplayTP = new JTextField();
panel_1.add(DisplayTP);
DisplayTP.setColumns(10);
JLabel lblGratPerParty = new JLabel("Grat Per Party");
panel_1.add(lblGratPerParty);
DispGPPP = new JTextField();
panel_1.add(DispGPPP);
DispGPPP.setColumns(10);
JLabel lblBanquetPay = new JLabel("Banquet Pay");
panel_1.add(lblBanquetPay);
DispBnqtPay = new JTextField();
panel_1.add(DispBnqtPay);
DispBnqtPay.setColumns(10);
DispEstPay = new JTextField("");
panel_1.add(DispEstPay);
DispEstPay.setColumns(10);
DispActualPC = new JTextField();
panel_1.add(DispActualPC);
DispActualPC.setColumns(10);
}
public static void main(String args[]) throws Exception{
getConnection();
post();
TemplatePractice frame = new TemplatePractice();
frame.setVisible(true);
frame.setSize(600,400);
}
public static Connection getConnection() throws Exception{
try {String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("connected");
return conn;
}catch(Exception e){System.out.println(e);}
return null;
}
public static void post() throws Exception{
final String var1 = "john";
final String var2 = "smith";
try{
Connection Con = getConnection();
PreparedStatement posted = Con.prepareStatement("INSERT INTO tablename(first,last) VALUES ('"+var1+"','"+var2+"')");
posted.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally {System.out.println("Insert Completed");}
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "SwingAction");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
}
}
}

Show MySQL data to JTextField

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class RegistrationForm extends JFrame {
private JPanel panel;
private JLabel user,pass,id;
private JTextField user1,pass1,id1;
private JButton save,signIn;
public Connection con;
public Statement stm;
public PreparedStatement pstm;
public RegistrationForm(){
setTitle("Register Account");
setLayout(new FlowLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\RenRen\\Documents\\NetBeansProjects\\JavaConnector\\src\\images\\reg.jpg")));
JLabel sign = new JLabel("Sign Up:");
sign.setBounds(100,95,80,30);
sign.setFont(new Font("Login",Font.ITALIC,20));
id= new JLabel("User ID");
user = new JLabel("Username:");
pass = new JLabel("Password:");
JLabel acc = new JLabel("Already have an Account?");
id.setBounds(300,95,80,30);
user.setBounds(130,140,80,20);
pass.setBounds(250,140,80,20);
acc.setBounds(250,230,150,20);
id1 = new JTextField(5);
user1 = new JTextField(10);
pass1 = new JPasswordField(10);
id1.setBounds(350,100,80,20);
user1.setBounds(130,160,110,20);
pass1.setBounds(250,160,110,20);
save = new JButton("Save");
signIn = new JButton("Sign In");
save.setBounds(150,200,90,20);
signIn.setBounds(250,200,90,20);
add(sign);
add(id);
add(id1);
add(user);
add(user1);
add(pass);
add(pass1);
add(save);
add(signIn);
add(acc);
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","");
stm=con.createStatement();
}
catch(Exception e)
{ JOptionPane.showMessageDialog(null, e);
}
ActionListener action = new ActionHandler();
save.addActionListener(action);
signIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(null, "Thank You!");
dispose();
LoginMain LM = new LoginMain();
LM.run();
}});
}
private class ActionHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == save){
String sql="Insert into logform(username,password)values(?,?)";
try{
pstm = con.prepareStatement(sql);
pstm.setString(1, user1.getText());
pstm.setString(2, pass1.getText());
pstm.execute();
JOptionPane.showMessageDialog(null, "Saved!");
}catch(Exception se){
JOptionPane.showMessageDialog(null, "Save Failed");
}
}
}
}
public void run(){
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args){
RegistrationForm rf = new RegistrationForm();
rf.run();
}
}
I want to show a data from MySQL database to JTextField. For example, a data from UserID in MySQL database is 1, I want to show that data in JTextField, and they can't edit text in JTextField. Can anyone help me please?
if UserID is integer use this code
jTextField.setText(String.valueOf(UserID);
//This make jTextField not editable
jTextField.setEditable(false);

update using prepared statement

I want to update my Database
When i enter the customer id in jTextbox after that pressing JButton OK then all respective data is extract from the Database is display in the remaining jTextfield in code
After displaying all respective database of that particular customer id that again edited for updation purpose then after clicking on the Update JButton all respective data is updated respective customer id
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public abstract class customer_details extends JFrame implements ActionListener
{
JTextField textFieldId;
JTextField textFieldId1;
JTextField textFieldId2;
JTextField textFieldId3;
JLabel l1;
JLabel l2;
JLabel l3;
JLabel l4;
JLabel l5;
JButton b1,b2;
Container c = getContentPane();
customer_details()
{
super("Shree Datta Digambar");
setBounds(140,250,777,555);
c.setLayout(null);
textFieldId = new JTextField();
textFieldId1 = new JTextField();
textFieldId2 = new JTextField();
textFieldId3 = new JTextField();
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
l1 = new JLabel("Update Customer Details:-");
l2 = new JLabel("Customer Id");
l3 = new JLabel("Customer Id");
l4 = new JLabel("Name");
l5 = new JLabel("Contact");
l1.setBounds(10,10,340,20);
l2.setBounds(10,20,140,70);
l3.setBounds(10,100,140,70);
l4.setBounds(100,100,140,70);
l5.setBounds(270,100,140,70);
textFieldId.setBounds(10,70,70,20);
textFieldId1.setBounds(10,160,70,20);
textFieldId2.setBounds(100,160,150,20);
textFieldId3.setBounds(270,160,90,20);
b1 = new JButton("Ok");
b1.setBounds(100,70,50,20);
b2 = new JButton("Update");
b2.setBounds(380,160,90,20);
c.add(b1);
c.add(b2);
c.add(l1);
c.add(l2);
c.add(l3);
c.add(l4);
c.add(l5);
c.add(textFieldId);
c.add(textFieldId1);
c.add(textFieldId2);
c.add(textFieldId3);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
b1.addActionListener(this);
b2.addActionListener(this);
}
public static void main(String[] args)
{
customer_details eeap=new customer_details() {};
}
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("You clicked the button");
if(e.getSource()==b1)
{
try
{
Connection con;
con = DriverManager.getConnection("jdbc:odbc:Dalvi");
java.sql.Statement st = con.createStatement();
PreparedStatement ps = con.prepareStatement("SELECT
customer_id,customer_name,customer_contact FROM customer_details WHERE
customer_id = ?");
ps.setString(1,textFieldId.getText());
ResultSet rs1=ps.executeQuery();
while(rs1.next())
{
textFieldId1.setText(rs1.getString(1));
textFieldId2.setText(rs1.getString(2));
textFieldId3.setText(rs1.getString(3));
}
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
JOptionPane.showMessageDialog(null,"Please Enter the Detail Correctly");
}
}
if(e.getSource()==b2)
{
try
{
Connection con;
con = DriverManager.getConnection("jdbc:odbc:Dalvi");
java.sql.Statement st = con.createStatement();
PreparedStatement ps = con.prepareStatement("UPDATE customer_details
SET customer_id = ? ,customer_name = ?, customer_contact =?
WHERE customer_id= ?");
ps.setString(1,textFieldId1.getText());
ps.setString(2,textFieldId2.getText());
ps.setString(3,textFieldId3.getText());
ps.setString(4,textFieldId.getText());
ps.executeUpdate();
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
JOptionPane.showMessageDialog(null,"Please Enter the Detail Correctly");
} } } }
Probably because your field types, especially customer_id, aren't Strings. Try something like this:
try (
Connection con = DriverManager.getConnection("jdbc:odbc:Dalvi");
PreparedStatement ps = con.prepareStatement("UPDATE customer_details SET customer_id = ?, customer_name = ? , customer_contact =? WHERE customer_id = ?");
)
{
ps.setInt(1, Integer.parseInt(textFieldId.getText()));
ps.setString(2,textFieldId1.getText());
ps.setString(3,textFieldId2.getText());
ps.setInt(4, Integer.parseInt(textFieldId3.getText()));
ps.executeUpdate();
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
JOptionPane.showMessageDialog(null,"Please Enter the Detail Correctly");
}
catch (NumberFormatException e)
{
}

Cant valid email textfield java

My problem is that i want to check if email textfield contains char "#".How am i supposed to do it?I also want to check if other textfields such as name, username, password are empty.Thanks alot in advance for your help. This application blowed my mind!
private JButton signupButton;
private JTextField name;
private JTextField email;
private JTextField username;
private JPasswordField pass;
private UserManager userManager;
public SignUpFrame (UserManager userManager){
super("Please fill in your Data");
userManager = new UserManager();
signupButton = new JButton("Sign Up!");
signupButton.addActionListener(new signupButtonListener());
name = new JTextField(15);
email = new JTextField(15);
username = new JTextField(15);
pass = new JPasswordField(15);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(5,2));
mainPanel.add(new JLabel("Name:"));
mainPanel.add(name);
mainPanel.add(new JLabel("Email:"));
mainPanel.add(email);
mainPanel.add(new JLabel("Username"));
mainPanel.add(username);
mainPanel.add(new JLabel("Password:"));
mainPanel.add(pass);
mainPanel.add(signupButton);
this.setContentPane(mainPanel);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
class signupButtonListener implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
String nam,emai,id,psw;
nam = name.getText();
emai= email.getText();
id = username.getText();
psw = pass.getText();
User u1 = new User(nam,emai,id,psw);
UserManager.userList.add(u1);
}
To check if a TextField is empty you can use if statements like:
if(name.getText().length() > 0){ nam = name.getText(); }
...
And for checking if there a char # in your email TextField you can use the .contains() method:
emai= email.getText();
if(emai.contains("#")){ ... }
I hope i was able to help you..
Try doing an if to test what the field hold ie
if(nam.equals("")){
//alert the user
}
You can do this with all the fields.
You could possible use regular expression for the email - something like
String emailreg = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";
Boolean result = emailAddress.matches(emailreg);
if(result == true){
//email is valid
}
Hope this helps.

JDBC ODBC with MS Access issue

I want to store a record but don't know what to do.
When i start entering the details of a customer, at that time database connectivity is successfully created but I fail to store the data in the database.
The procedure is correct to create the database but I can't enter the details, what can I do?
Here is the code:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.*;
//package p1;
public abstract class New_Customer extends JFrame implements ActionListener
{
JTextField textFieldId;
JTextField textFieldName;
JTextField textFieldContactNo;
JLabel l1;
JLabel l2;
JLabel l3;
JLabel l4;
JLabel l5;
JLabel l6;
JComboBox combo;
String course[] = {"Navakal","SandhyaKal","Pudhari","MidDay","Inqlab","BusinessLine","Mumbai Samachar","GujrajSamachar","KarnatakMalla","Vartahar","PunyaNagari"};
JButton b1;
JButton b2;
Container c = getContentPane();
New_Customer()
{
super("Shree DattaDigambar Samarth");
setBounds(140,250,777,555);
c.setLayout(null);
textFieldId = new JTextField();
textFieldName = new JTextField();
textFieldContactNo = new JTextField();
l1 = new JLabel("New Customer Entry");
l2 = new JLabel("Building No");
l3 = new JLabel("Customer Name");
l4 = new JLabel("Contact No");
l5 = new JLabel("Paper");
combo = new JComboBox(course);
l1.setBounds(10,10,340,20);
l2.setBounds(10,20,140,70);
l3.setBounds(110,20,140,70);
l4.setBounds(300,50,140,20);
l5.setBounds(400,50,140,20);
textFieldId.setBounds(10,70,70,20);
textFieldName.setBounds(110,70,180,20);
textFieldContactNo.setBounds(300,70,90,20);
combo.setBounds(400,70,130,20);
b1 = new JButton("Add paper");
b2 = new JButton("Ok");
b1.setBounds(10,100,100,20);
b2.setBounds(10,160,50,20);
c.add(combo);
c.add(b1);
c.add(b2);
c.add(l1);
c.add(l2);
c.add(l3);
c.add(l4);
c.add(l5);
c.add(textFieldId);
c.add(textFieldName);
c.add(textFieldContactNo);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
b1.addActionListener(this);
b2.addActionListener(this);
}
public static void main(String[] args)
{
New_Customer nc=new New_Customer() {};
}
public void actionPerformed(ActionEvent e)
{
System.out.println("You clicked the button");
if(e.getSource()==b1)
{
}
if(e.getSource()==b2)
{
try
{
Connection con;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:devendra");
try
{
java.sql.Statement st = con.createStatement();
PreparedStatement ps = con.prepareStatement(null);
ResultSet rs = ps.executeQuery("insert into Customer values(?,?,?,?)");
while(rs.next())
{
ps.setString(1,textFieldId.getText());
ps.setString(2,textFieldName.getText());
ps.setString(3,textFieldContactNo.getText());
ps.setString(4,combo.getName());
}
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
}
}
catch (ClassNotFoundException | SQLException ee)
{
System.out.println("Error:connection not created");
}
}
}
}
First of all to insert values in database, you should use executeUpdate() method.
And this method does not return any ResultSet.
So Change your code
PreparedStatement ps = con.prepareStatement("insert into Customer values(?,?,?,?)");
ps.setString(1,textFieldId.getText());
ps.setString(2,textFieldName.getText());
ps.setString(3,textFieldContactNo.getText());
ps.setString(4,combo.getName());
ps.executeUpdate();

Categories

Resources