make search result appear in the same page (Swing program) - java

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)

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 to make JFrame login form work?

I am doing a project on library management in java using swing on eclipse. When I click on the login button nothing happens. The mysql jdbc driver is loaded and I am getting the connection but no label appears. Please tell me what to do. Here is my code.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class Loginscreen implements ActionListener {
JFrame logframe;
JButton bt;
JLabel lid, lpass, lmsg;
JTextField tid;
JPasswordField pass;
JPanel p1;
Font ft, ft2;
Connection conn;
public Loginscreen() {
logframe = new JFrame("Login");
logframe.setSize(1366, 720);
logframe.setVisible(true);
lid = new JLabel("User ID");
lpass = new JLabel("Password");
lmsg = new JLabel();
ft = new Font("Arial", Font.BOLD, 30);
ft2 = new Font("Arial", Font.PLAIN, 20);
tid = new JTextField();
pass = new JPasswordField();
p1 = new JPanel();
bt = new JButton("Login");
logframe.add(p1);
p1.setLayout(null);
p1.setBackground(new Color(160, 82, 45));//Background Color Set
lid.setBounds(450, 200, 500, 30);
p1.add(lid);
lid.setFont(ft);
tid.setBounds(650, 200, 200, 30);
p1.add(tid);
tid.setFont(ft2);
lpass.setBounds(450, 300, 500, 30);
p1.add(lpass);
lpass.setFont(ft);
pass.setBounds(650, 300, 200, 30);
p1.add(pass);
bt.setBounds(600, 430, 100, 50);
p1.add(bt);
bt.setFont(new Font("Segoe Script", Font.BOLD, 22));
bt.setBackground(new Color(173, 216, 230));
lmsg.setBounds(450, 510, 500, 30);
p1.add(lmsg);
bt.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == bt) {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_lib", "root", "admin");
String i = tid.getText();//get the user id
char[] pwd = pass.getPassword();//get the password
String spwd = new String(pwd);//converting char to string
String query = "select * from tbl_user where id=? and password=?";
PreparedStatement p = conn.prepareStatement(query);
p.setString(1, i);
p.setString(2, spwd);
ResultSet rs = p.executeQuery();
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
lmsg.setText("Invalid User ID or Password");
} else {
lmsg.setText("Invalid User ID or Password");
}
rs.close();
conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
I guess you dont set the text when it succeeds.
Also make sure
while(rs.next())
{
count=count+1;
}
terminates.
Also secure your query against SQL-Injection (just realized this)
For these kinds of debugging problems I recommend UnitTesting (basically just test how far the program goes, how long it takes, if it terminates etc).
Also before you post a question, do us a favor to add comments and format the GUI-stuff properly...it looks horrible :/
EDIT:
if(count==1)
{
lmsg.setText("Invalid User ID or Password");
}
else
{
lmsg.setText("Invalid User ID or Password");
}
Does not make sense to me... Whatever happens you return an error

Adding JList to show basic DB information

My goal is to put a JList with the data from my DB over the 2 JTextFields, but i dont know how to do it. Do you guys and girls know what the mistake is and how I can fix it?
(The Variable personList has all the Data in it. Just need to put it in JList. But this Variable personList is a ArrayList.)
public class Datenbank2 extends JFrame {
public Datenbank2() {
super("Datenbank der Lehrlinge 1 Lehrjahr");
JPanel centerPanel = new JPanel();
JPanel southPanel = new JPanel();
JPanel linkesPanel = new JPanel();
this.setBounds(600, 300, 500, 450);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager
.getConnection("jdbc:sqlite:C://Users/N-YP/workspace/UebungJava/ch/nyp/uebungen/datenbanken/SqLiteDB.db");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM Person");
ArrayList<JLabel> personList = new ArrayList<JLabel>();
while (rs.next()) {
String vorname = rs.getString("Vorname");
String nachname = rs.getString("Nachname");
personList.add(new JLabel(vorname + " " + nachname));
System.out.println(vorname + " " + nachname);
}
JTextField eingVorname = new JTextField();
JTextField eingNachname = new JTextField();
eingVorname.setPreferredSize(new Dimension(230, 30));
eingNachname.setPreferredSize(new Dimension(230, 30));
BorderLayout borderLayout = new BorderLayout();
this.getContentPane().setLayout(borderLayout);
this.add(centerPanel, BorderLayout.CENTER);
this.add(southPanel, BorderLayout.SOUTH);
centerPanel.add(linkesPanel, BorderLayout.WEST);
FlowLayout flowLayout = new FlowLayout();
centerPanel.setLayout(flowLayout);
for (JLabel personLabel : personList) {
centerPanel.add(personLabel);
}
southPanel.setLayout(flowLayout);
southPanel.add(eingVorname);
southPanel.add(eingNachname);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(0);
System.out
.println("Datenbank geöffnet (muss später aber wieder geschlossen werden).");
}
}
public static void main(String[] args) {
Datenbank2 javamitdb = new Datenbank2();
javamitdb.setVisible(true);
}
}
Thank you and have a nice Day.
Well use DefaultListModel and its addElement() method in your while loop to add each result, like the following:
listModel = new DefaultListModel();
while (rs.next()) {
String vorname = rs.getString("Vorname");
String nachname = rs.getString("Nachname");
listModel.addElement(vorname + " " + nachname);
System.out.println(vorname + " " + nachname);
}
//then create a list with this model
list = new JList(listModel);
Take a look at How to Use Lists for further information.

Give a layout that suits the components

I'm struggling to give a good layout to my Swing components. Currently FlowLayout being is used, but it doesn't look pretty. My requirement is to display the label l0 in top line. Then the label l1, combobox c1 and button b1 in second column (center aligned). Finally, the output that gets displayed in Jtable beneath. How do I do this?
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 = new JTable();;
String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
String from;
Vector v = new Vector();
JMenuBar menu = new JMenuBar();
r_search_1()
{
frame1 = new JFrame("yippee");
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.setLayout(new FlowLayout());
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);
frame1.add(l0);
frame1.add(l1);
//frame1.add(b1);
frame1.setVisible(true);
frame1.setSize(1000, 400);
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);
frame1.add(c1);
frame1.add(b1);
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 FlowLayout());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
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);
//table.close()
}
public static void main(String args[]) {
new r_search_1();
}
}
This is my requirement:
Notes
It is named PoorlySpecifiedLayout because you forgot the part about.. "and (if resizable) with extra width/height."
The UI is naturally taller than seen above. It was shortened to make a better screenshot.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class PoorlySpecifiedLayout {
// the GUI as seen by the user (without frame)
JPanel ui = new JPanel(new BorderLayout(5,5));
String[] comboValues = {
"String to pad combo."
};
String[] tableHeader = {
"Section Name","Report Name","Contact","Link"
};
String[][] tableBody = {{"", "", "", ""}};
PoorlySpecifiedLayout() {
initUI();
}
public final void initUI() {
ui.setBorder(new EmptyBorder(20,20,20,20));
JPanel top = new JPanel(new BorderLayout(15, 5));
ui.add(top, BorderLayout.PAGE_START);
top.add(new JLabel(
"Fetching search results", SwingConstants.CENTER));
JPanel controls = new JPanel(new FlowLayout(SwingConstants.LEADING, 10, 5));
top.add(controls, BorderLayout.PAGE_END);
controls.add(new JLabel("Search:"));
controls.add(new JComboBox(comboValues));
JButton submit = new JButton("submit");
Insets padButton = new Insets(5,20,5,20);
submit.setMargin(padButton);
controls.add(submit);
JTable table = new JTable(tableBody, tableHeader);
ui.add(new JScrollPane(table));
}
public final JComponent getUI(){
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
PoorlySpecifiedLayout psl = new PoorlySpecifiedLayout();
JFrame f = new JFrame("Poorly Specified Layout");
f.add(psl.getUI());
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
Edit: as per advice by Andrew Thompson - a picture.
Here is an example of how to do it using BorderLyout for the search / submit row and table, and adding the title in a border title instead of a label:
public class Search extends JFrame {
private final static String TITLE = "Fetching Search Results";
private final static String[] COLUMN_HEADERS = {"Section name", "Report name", "Contact", "Link"};
private final static String[] SEARCH_OPTIONS = {"AAAAA", "BBBBB"};
Search() {
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), TITLE, TitledBorder.CENTER, TitledBorder.TOP, new Font("Arial", Font.PLAIN, 20), Color.RED));
JPanel topPanel = new JPanel();
JLabel searchLabel = new JLabel("Search:");
JComboBox<String> searchBox = new JComboBox<>(SEARCH_OPTIONS);
JButton submitButton = new JButton("Submit");
topPanel.add(searchLabel);
topPanel.add(searchBox);
topPanel.add(submitButton);
JTable table = new JTable(new String[34][4], COLUMN_HEADERS);
mainPanel.add(topPanel, BorderLayout.PAGE_START);
mainPanel.add(new JScrollPane(table));
setContentPane(mainPanel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[]) {
new Search();
}
}
If you want the title as a label, you can put another panel for it.

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