connecting JComboBox to JTextField [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have populated my JComboBox with the value of same database table and I need an idea to display the value of JComboBox as it is in JTextField.
I am not using Array list instead I am using database table(mysql),below is the program
import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
class Test extends JFrame implements ActionListener
{
JButton b1,b2;
JComboBox jc;
String name;
JTextField t1;
Connection con,conn;
Statement st;
PreparedStatement pst;
ResultSet rs,rs1;
Test()
{
setLayout(null);
JLabel l1=new JLabel("USER SELECTION :");
l1.setBounds(100, 100, 150, 60);
add(l1);
JComboBox jc = new JComboBox();
jc.setBounds(230,114,120,30);
jc.addActionListener(this);
add(jc);
JButton b1=new JButton("GENERATE PART NO. :");
b1.setBounds(70, 340, 170, 30);
b1.addActionListener(this);
add(b1);
t1=new JTextField (10);
t1.setBounds(270, 340, 200, 30);
add(t1);
JButton b2=new JButton("BACK");
b2.setBounds(190, 420,120, 30);
b2.addActionListener(this);
add(b2);
setSize(500, 500);
setResizable(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try{
Class.forName("com.mysql.jdbc.Driver");
con= DriverManager.getConnection("jdbc:mysql://localhost/d02","root","");
st = con.createStatement();
String s = "select Userdata from user";
rs = st.executeQuery(s);
while(rs.next())
{
String name = rs.getString("Userdata");
jc.addItem(rs.getString("Userdata"));
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "ERROR");
}
finally
{
try
{
//st.close();
rs.close();
//con.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("GENERATE PART NO. :"))
{
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/d02","root","");
String query="select value from user where Userdata=?";
PreparedStatement pst=conn.prepareStatement(query);
String tmp=(String)jc.getSelectedItem().toString();
if(jc.getSelectedItem()!=null)
pst.setString(1,tmp);
ResultSet rs1=pst.executeQuery();
while(rs1.next())
{
String add=rs1.getString("value");
t1.setText(add);
}
}
catch(Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
if(str.equals("BACK")==true)
{
new categ();
setVisible(false);
}
}
}
public static void main(String[] args) throws IOException
{
Test td=new Test();
}
}

Add ItemListener to your JComboBox
jc.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
cmbMyItemStateChanged(evt);
}
});
listener method:
private void cmbMyItemStateChanged(java.awt.event.ItemEvent evt){
String value = jc.getSelectedItem().toString();
if(jc.getSelectedItem()!=null){
}
}

Related

Add data into MySQL Database using Eclipse

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");
}
}
}
}

How can I retrieve values from a DB and load them into a JTable?

I'm trying to load values from a database and list them into a jtable. I have the statement executing properly, however when I load the application nothing appears in the table space, nor do I receive any error messages. Is there a statement missing? I haven't worked with jtable before. I've edited the original post to contain all of my code to bring into context
//imports
public class viewMusic extends JFrame {
static Connection conn = null;
static viewMusic frame = new viewMusic();
private JPanel contentPane;
private JTable table;
private JTable table_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
viewMusic frame = new viewMusic();
//frame.setVisible(true);
try { //Login details for the DB.
String userName = "root";
String password = "";
String url = "jdbc:mysql://localhost/music";
conn = DriverManager.getConnection(url, userName, password);
//JOptionPane.showMessageDialog(null, "Connected");
} catch (Exception e) { //Error is DB connection is unsuccessful .
JOptionPane.showMessageDialog(null, "Cannot connect to database server");
// System.err.println(e.getMessage());
System.err.println(e.getStackTrace());
}
} catch (Exception e) {
e.printStackTrace();
}
Statement stmt;
try {
stmt = conn.createStatement();
DefaultTableModel model = new DefaultTableModel(new String[]{"Artist_Name", "Album_Title", "Record_Label", "Genre", "Year", "Format"}, 0);
JTable table = new JTable(model);
String query="SELECT * from cds";
System.out.println(query);
ResultSet rs = stmt.executeQuery(query);
String a = "artist";
String b = "album title";
String c = "record label";
String d = "genre";
String e = "year";
String f = "format";
model.addRow(new Object[]{a, b, c, d, e, f});
table.setModel(model);
JScrollPane scrollpane = new JScrollPane(table);
frame.getContentPane().add(scrollpane);
frame.setSize(600, 500);
frame.setVisible(true);
} catch (Exception e) { //Error is DB connection is unsuccessful .
JOptionPane.showMessageDialog(null, "Cannot connect");
// System.err.println(e.getMessage());
System.err.println(e.getStackTrace());
}
} //End of run()
});
} //End of main
/**
* Create the frame.
*/
public viewMusic() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table_1 = new JTable();
table_1.setBounds(25, 64, 551, 250);
contentPane.add(table_1);
JLabel lblStatus = new JLabel("Connection Status");
lblStatus.setBounds(399, 18, 149, 13);
contentPane.add(lblStatus);
lblStatus.setText("Connecting to DB..");
}
}
You need to add the JTable to the JFrame
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class ViewMusic extends JFrame {
private static final long serialVersionUID = 1L;
// static Connection conn = null;
static ViewMusic frame = new ViewMusic();
private JPanel contentPane;
private static JTable table;
private static DefaultTableModel model;
// private JTable table_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
model = new DefaultTableModel(new Object[] { "Artist_Name",
"Album_Title", "Record_Label", "Genre", "Year", "Format" },
0);
String a = "artist";
String b = "album title";
String c = "record label";
String d = "genre";
String e = "year";
String f = "format";
model.addRow(new Object[] { a, b, c, d, e, f });
table.setModel(model);
frame.repaint();
}
});
} // End of main
/**
* Create the frame.
*/
public ViewMusic() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table = new JTable();
JScrollPane scrollpane = new JScrollPane(table);
scrollpane.setBounds(25, 64, 551, 250);
contentPane.add(scrollpane);
JLabel lblStatus = new JLabel("Connection Status");
lblStatus.setBounds(399, 18, 149, 13);
contentPane.add(lblStatus);
lblStatus.setText("Connecting to DB..");
setVisible(true);
}
}

Loading data from a sqlite database in Java?

I am new to the world of Java and sqlite database. I was trying out some codes about loading data from a database into a tabular view using java in eclipse. Now, here is the thing, when my data loads from the database, i want to add an extra column which contains a checkbox(unchecked). Can someone suggest me how do i implement it? Please note that when i run the code, it works absolutely fine and shows no error....I am able to see all the records in my table without any error. Just want an unchecked checkbox to be added to each row so that when i click on it, i can do something. Thats my goal..
Here is what i tried so far.. I have two classes namely:-
1. sqliteConnection.java(which is for connection )
2. employeeinfo.java class which is for loading the data from the database into a table and other functionalities.
import java.sql.*;
import javax.swing.*;
public class sqliteConnection {
Connection conn = null;
public static Connection dbConnector()
{
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\user\\Downloads\\Documents\\MyJavaProjects\\Phone\\Employee.sqlite");
JOptionPane.showMessageDialog(null, "Connection Succesful");
return conn;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
public sqliteConnection() {
// TODO Auto-generated constructor stub
}
}
employeeinfo.java --
import java.awt.BorderLayout;
public class employeeinfo extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
employeeinfo frame = new employeeinfo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connection = null;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
public employeeinfo() {
connection = sqliteConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 842, 457);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblJframe = new JLabel("Jframe2");
lblJframe.setBounds(47, 37, 46, 14);
contentPane.add(lblJframe);
JButton btnLoad = new JButton("Load");
btnLoad.addActionListener(new ActionListener() {
PreparedStatement pat;
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select eid,Name,Surname,Age from EmployeeInfo ";
pat = connection.prepareStatement(query);
ResultSet rs = pat.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e)
{
}
}
});
btnLoad.setBounds(104, 33, 89, 23);
contentPane.add(btnLoad);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(429, 48, 370, 232);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JLabel lblName = new JLabel("EID");
lblName.setBounds(10, 98, 46, 21);
contentPane.add(lblName);
textField = new JTextField();
textField.setBounds(107, 99, 126, 20);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblName_1 = new JLabel("Name");
lblName_1.setBounds(10, 154, 46, 14);
contentPane.add(lblName_1);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(107, 151, 126, 20);
contentPane.add(textField_1);
JLabel lblSurname = new JLabel("Surname");
lblSurname.setBounds(10, 204, 46, 14);
contentPane.add(lblSurname);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(104, 201, 126, 20);
contentPane.add(textField_2);
JLabel lblAge = new JLabel("Age");
lblAge.setBounds(10, 278, 46, 14);
contentPane.add(lblAge);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(104, 275, 126, 20);
contentPane.add(textField_3);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
PreparedStatement pat;
try {
String query = "insert into EmployeeInfo(EID,name,surname,age) values(?,?,?,?)";
pat = connection.prepareStatement(query);
pat.setString(1, textField.getText());
pat.setString(2, textField_1.getText());
pat.setString(3, textField_2.getText());
pat.setString(4, textField_3.getText());
pat.execute();
JOptionPane.showMessageDialog(null, "Data Saved successfully");
pat.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
btnSave.setBounds(72, 349, 89, 23);
contentPane.add(btnSave);
JButton btnClear = new JButton("Clear");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
textField_1.setText("");
textField_2.setText("");
textField_3.setText("");
}
});
btnClear.setBounds(206, 349, 89, 23);
contentPane.add(btnClear);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
String query="Update EmployeeInfo set EID='"+textField.getText()+"',Name='"+textField_1.getText()+"'"
+",Surname='"+textField_2.getText()+"',Age='"+textField_3.getText()+"'where EID='"+textField.getText()+"'";
// JOptionPane.showMessageDialog(null, query);
PreparedStatement pst=connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Data Saved successfully");
pst.close();
}
catch(Exception f)
{
f.printStackTrace();
}
}
});
btnUpdate.setBounds(323, 349, 89, 23);
contentPane.add(btnUpdate);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
String query="delete from EmployeeInfo where EID='"+textField.getText()+"'";
// JOptionPane.showMessageDialog(null, query);
PreparedStatement pst=connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Data deleted successfully");
pst.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
btnDelete.setBounds(453, 349, 89, 23);
contentPane.add(btnDelete);
}
}
My suggestion is you first go through this article, it's a very simpler way of loading data from ResultSet to DefaultTableModel. After this you have to make some small changes like, you have to add another column heading to the Vector of columnNames and add a column for check boxes. Then when you process each row from the ResultSet you need to add a Boolean value to the row Vector with a checkbox .

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);

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