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)
{
}
Related
I tried to make a simple programming that allows student's data to be added, updated, deleted and viewed for my assignments. I'm already stuck at adding part. What is the correct syntax /code to use in order to insert data into the database?
I'm using Eclipse IDE software and XAMPP for this programming.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class PracticalExercise2 extends JFrame implements ActionListener{
Connection con;
Statement stmt;
JLabel lblname, lblmatricnumber, lblproject,lbltajuk;
JTextField txtname, txtmatricnumber , txtproject;
JButton btntest,btnadd,btnupdate,btndelete,btnview;
String user,pass;
ResultSet rs;
JTabbedPane myTab;
JPanel pnladd,pnlupdate,pnldelete,pnlview;
public PracticalExercise2() {
setLayout(null);
setSize(400,400);
setTitle("Registration Form using JTabbedPane");
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//GUI SETTING FOR FORM
lbltajuk = new JLabel("Registration Form");
lbltajuk.setBounds(10, 20, 350, 50);
lbltajuk.setFont(new Font("Arial",Font.BOLD,32));
lbltajuk.setForeground(Color.BLUE);
add(lbltajuk);
//JTabbedPane is also a panel
myTab = new JTabbedPane();
myTab.setBounds(20,70,350,200);
add(myTab);
pnladd = new JPanel();
pnlupdate = new JPanel();
pnldelete = new JPanel();
pnlview = new JPanel();
//Create and add Tab
myTab.addTab("Add Data", pnladd);
myTab.addTab("Update Data", pnlupdate);
myTab.addTab("Delete Data", pnldelete);
myTab.addTab("View Data", pnlview);
btntest = new JButton("Test Connection");
btntest.setBounds(120, 300, 150, 30);
add(btntest);
btntest.addActionListener(this);
add();
}
public static void main(String[] args) {
new PracticalExercise2();
}
void add()
{
pnladd.setLayout(null);
lblname = new JLabel("Nama :");
lblname.setBounds(20,20,100,30);
pnladd.add(lblname);
lblmatricnumber = new JLabel("No Matrik :");
lblmatricnumber.setBounds(20,60,100,30);
pnladd.add(lblmatricnumber);
lblproject = new JLabel("Projek :");
lblproject.setBounds(20,100,100,30);
pnladd.add(lblproject);
txtname = new JTextField();
txtname.setBounds(110,20,200,30);
pnladd.add(txtname);
txtmatricnumber = new JTextField();
txtmatricnumber.setBounds(110,60,200,30);
pnladd.add(txtmatricnumber);
txtproject = new JTextField();
txtproject.setBounds(110,100,200,30);
pnladd.add(txtproject);
btnadd = new JButton("Add Data");
btnadd.setBounds(120, 140, 100, 30);
pnladd.add(btnadd);
btnadd.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btntest)
{
// 1. load driver
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException x)
{
JOptionPane.showMessageDialog(null, "mySQL Driver cannot connect.");
}
// 2. create/open connection
try {
//testing the connection to database.
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/practicaltask2", "root", "");
JOptionPane.showMessageDialog(null, "No connection error.");
} catch (SQLException y) {
JOptionPane.showMessageDialog(null, "Connection error.");
}
}
if(e.getSource() == btnadd)
{
String name , matric , project;
name = txtname.getText();
matric = txtmatricnumber.getText();
project = txtproject.getText();
try {
PreparedStatement stmnt = con.prepareStatement("insert into pelajar(NULL,nama,nomatrik,projek)values(NULL,?,?,?)", Statement.RETURN_GENERATED_KEYS);
((PreparedStatement) stmt).setString(2,name);
((PreparedStatement) stmt).setString(3,matric);
((PreparedStatement) stmt).setString(4,project);
JOptionPane.showMessageDialog(null, "Record Added Successfuly");
txtname.setText("");
txtmatricnumber.setText("");
txtproject.setText("");
}
catch (Exception a)
{
JOptionPane.showMessageDialog(null, "Failed to add data");
}
}
}
}
So, this is a program in swing for implementing a search functionality. It runs perfectly well. No problems there. My requirement is to make the search results appear beneath the same page. In this code, I have made the results to appear in a new Jframe that opens a new window. I basically don't want this. I want to make the search result appear in the same page. So, should I modify the code ? Any form of help is appreciated. :) Thanks !
This is my code:-
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class r_search_1 extends JFrame implements ActionListener {
JFrame frame1;
JLabel l0, l1, l2;
JComboBox c1;
JButton b1;
Connection con;
ResultSet rs, rs1;
Statement st, st1;
PreparedStatement pst;
String ids;
static JTable table;
String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
String from;
Vector v = new Vector();
r_search_1()
{
l0 = new JLabel("Fetching Search Results...");
l0.setForeground(Color.blue);
l0.setFont(new Font("Serif", Font.BOLD, 20));
l1 = new JLabel("Search");
b1 = new JButton("submit");
l0.setBounds(100, 50, 350, 40);
l1.setBounds(75, 110, 75, 20);
b1.setBounds(150, 150, 150, 20);
b1.addActionListener(this);
setTitle("Search Executive Reports ");
setLayout(null);
//setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(l0);
add(l1);
add(b1);
try
{
File dbFile = new File("executive_db.accdb");
String path = dbFile.getAbsolutePath();
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
st = con.createStatement();
rs = st.executeQuery("select index_name from Index1");
while (rs.next())
{
ids = rs.getString(1);
v.add(ids);
}
c1 = new JComboBox(v);
c1.setEditable(true);c1.setSelectedItem("");
c1.setBounds(150, 110, 150, 20);
add(c1);
st.close();
rs.close();
} catch (Exception e) {
}
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) {
showTableData();
}
}
public void showTableData()
{
frame1 = new JFrame("Database Search Result");
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.setLayout(new BorderLayout());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
from = (String) c1.getSelectedItem();
String section_name = "";
String report_name = "";
String contact_name = "";
String link = "";
try
{
pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
+ "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID ) LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID "
+ " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
ResultSet rs = pst.executeQuery();
int i = 0;
while (rs.next()) {
section_name = rs.getString("Section_Name");
report_name = rs.getString("Report_Name");
contact_name = rs.getString("Contact_Name");
link = rs.getString("Link");
model.addRow(new Object[]{section_name, report_name, contact_name, link});
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(1000, 400);
}
public static void main(String args[]) {
new r_search_1();
}
}
Do not use Null layout. Use a BorderLayout.
All your search functionality should be in the center panel.
add(mySearchPanel, BorderLayout.CENTER);
Your results should be in the south panel. That way it will not shrink the center panel.
add(myResultsPanel, BorderLayout.SOUTH);
If there is nothing in the south panel, then it will shrink away making it seem like it is not there.
So, going into a little more detail, your l0,l1, and b1 components should go into a panel (say myTopPanel), and be added to the center. Your scroll component should be added to the bottom panel.
setTitle("Search Executive Reports ");
setLayout(new BorderLayout());
myTopPanel.add(l0);
myTopPanel.add(l1);
myTopPanel.add(b1);
add(myTopPanel, BorderLayout.CENTER)
add(scroll, BorderLayout.CENTER)
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();
Im trying to populate JTable with MySql data. Thing is when i run Login class, i receive message "java.SQLException: No value specified for parameter 2" and when i run JTable class I keep receiving java.lang.NullPointerException error. I have three classes : 1-Connection to DB:
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class javaconnect {
Connection conn = null;
public static Connection ConnecrDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb",
"root", "root");
JOptionPane.showMessageDialog(null, "Connected");
return con;
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
return null;
}
}
The second class is login frame:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.*;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JFrameLogIn extends JFrame {
Connection conn =null;
ResultSet rs = null;
PreparedStatement pst = null;
private JPanel contentPane;
private JPasswordField txt_Password;
private JTextField txt_Username;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrameLogIn frame = new JFrameLogIn();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JFrameLogIn() {
conn=javaconnect.ConnecrDB();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 375, 214);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setFont(new Font("Tahoma", Font.BOLD, 13));
lblUsername.setBounds(126, 45, 80, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setFont(new Font("Tahoma", Font.BOLD, 13));
lblPassword.setBounds(126, 82, 69, 14);
contentPane.add(lblPassword);
txt_Password = new JPasswordField();
txt_Password.setBounds(218, 82, 109, 20);
contentPane.add(txt_Password);
txt_Username = new JTextField();
txt_Username.setBounds(216, 43, 111, 20);
contentPane.add(txt_Username);
txt_Username.setColumns(10);
JButton cmd_Login = new JButton("Login");
cmd_Login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sql = "Select * from clients where username=? and password=?";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txt_Username.getText());
pst.setString(1, txt_Password.getText());
rs = pst.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Username and Password are correct");
}
else {
JOptionPane.showMessageDialog(null, "Username and Password are not correct");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
cmd_Login.setBounds(218, 125, 80, 23);
contentPane.add(cmd_Login);
}
}
and the last one is JTable
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.sql.*;
import net.proteanit.sql.DbUtils;
public class JTable1 extends JFrame {
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
private JPanel contentPane;
private JTable table_Admins;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JTable1 frame = new JTable1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JTable1() {
conn = javaconnect.ConnecrDB();
UpdateTable ();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table_Admins = new JTable();
table_Admins.setBounds(30, 28, 378, 54);
contentPane.add(table_Admins);
}
private void UpdateTable () {
try {
String sql = "SELECT *FROM menu";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I am trying to figure out what is the problem but cannot find the solution. Connection works. I would really appreciate your help in fixing this error.
The second parameter in your PreparedStatment is not set. You should replace
pst.setString(1, txt_Password.getText());
with
pst.setString(2, txt_Password.getText());
Edit: Note that JPassword.getText() is deprecated meaning that you should no longer use it. getPassword() is provided in its place:
pst.setString(2, new String(txt_Password.getPassword()));
you can add a check to the code
rs = pst.executeQuery();
if (rs!=null){
if(rs.next()){
JOptionPane.showMessageDialog(null, "Username and Password are correct");
}
else {
JOptionPane.showMessageDialog(null, "Username and Password are not correct");
}
}
And Also in your JTable1 class
if (rs!=null)
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
private void UpdateTable () {
conn = javaconnect.ConnecrDB();// connection and query should be in same place
try {
String sql = "SELECT *FROM menu";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
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());