Add data into MySQL Database using Eclipse - java

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

Related

Trouble inserting data into SQLite database. Can't get a connection to the database. Why isn't it working?

I created a program with a few lines of code after getting some advice her on Stackoverflow. My problem is that I can't connect to the database. I get an error called: [SQLITE_ERROR] SQL error or missing database (no such table: PasswordTable).
I created the database via SQLite and also get a successfull connection but cannot insert data.
The database in SQLiteManager is called MyDB.sqlite and the table is called PasswordTable
...I am thankful for any help I can get :)
Also: Did I do the implementation of the inner class right? Is this appropriate?
Code is as follows:
import javax.swing.*;
public class Main {
public static void main (String [] args) {
JFrame frame = new JFrame ();
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(700, 300);
frame.add(new FrameFunctionality ());
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class FrameFunctionality extends JPanel {
JLabel label1;
JTextField tf1;
JButton but1;
Database db1;
public FrameFunctionality() {
setLayout(null);
//----Add a label to the frame
label1 = new JLabel("Passwort eingeben:");
label1.setBounds(10, 20, 150, 40);
add (label1);
//-------Add a tf to the frame
tf1 = new JTextField ();
tf1.setBounds(10, 50, 150, 40);
add (tf1);
//---Add a button to the frame
but1 = new JButton ("Save");
but1.setBounds(10, 100, 100, 50);
but1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
db1 = new Database ();
db1.insertData();
}
});
add (but1);
}
public class Database { //Inner Class
Connection con = null;
DriverManager man1 = null;
PreparedStatement pst = null;
public Database () {
//------Connect to the database
try {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:MyDB.sqlite");
System.out.println("Connection: Ok!");
} catch (Exception e) {
System.out.println("Error1: " + e.getMessage());
}
}
//Insert data into the database
public void insertData () {
try {
String query = "INSERT INTO PasswordTable (Passwort) VALUES
(?)";
pst = con.prepareStatement(query);
pst.setString(1, tf1.getText());
pst.execute();
}catch (Exception e) {
System.out.println("Error2: " + e.getMessage());
}
}
}
}

connecting JComboBox to JTextField [duplicate]

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){
}
}

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

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

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)

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