Making a program which is GUI. A user can enter values in text fields and data is saved on database. But i want to display that row in which data is saved with button click on eclipse console.Just like that
========================
title year
========================
300 2006
Data Saved!
My code is
public class Db extends JFrame{
private JTextField value1;
private JTextField value2;
private JLabel label1;
private JLabel label2;
private JButton b1;
private Connection conn;
private PreparedStatement pre;
private ResultSet set;
private ResultSetMetaData meta;
String server = "jdbc:mysql://localhost/demo";
String user="root";
String pass="1";
public Db(){
super("Frame");
getContentPane().setLayout(null);
value1= new JTextField();
value1.setBounds(222, 86, 128, 27);
getContentPane().add(value1);
value2= new JTextField();
value2.setBounds(222, 160, 128, 27);
getContentPane().add(value2);
label1= new JLabel("Enter Value 1 :");
label1.setFont(new Font("Tahoma", Font.PLAIN, 21));
label1.setBounds(33, 77, 146, 37);
getContentPane().add(label1);
label2= new JLabel("Enter Value 2 :");
label2.setFont(new Font("Tahoma", Font.PLAIN, 21));
label2.setBounds(33, 151, 146, 37);
getContentPane().add(label2);
b1= new JButton("Save");
b1.setBounds(161, 228, 102, 37);
getContentPane().add(b1);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
// create our java prepared statement using a sql update query
conn=DriverManager.getConnection(server,user,pass);
//query
String query = "insert into movies(title,year) values (?,?)";
//create prepared statement
pre = conn.prepareStatement(query);
//parameter
pre.setString(1, value1.getText());
//second parameter will be integer so conversion
String w = value2.getText();
int p =Integer.parseInt(w);
pre.setInt(2, p);
// call executeUpdate to sql update statement return integer rowsaffected
int rowsaffect = pre.executeUpdate();
//message come when query run
JOptionPane.showMessageDialog(null, "Query Executed Successfully");
}
catch(Exception e1){
JOptionPane.showMessageDialog(null, e1.getMessage());
}
}});
setSize(450, 400);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Main
public class Main {
public static void main(String[] args) {
Db obj = new Db();
}
}
if i understand your question correctly.
the easy way is first check does execute update successful ,if yes then print title year which you pass to the query .
int rowsaffect = pre.executeUpdate();
if(rowsaffect >0){
System.out.println("========================");
System.out.println("title year");
System.out.println("========================");
System.out.println(value1.getText()+" "+p);
}
this an example you have to correctly add spaces to get correct output.you may need to programmatically count how much spaces need to show output correctly because it depend on title, year value length
Related
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
enter code hereHi I'm new developer in Java I want to put a JComboBox in a public class to get the selected item but Java don't recognize it for example i want to do this.
myComboBox.getSelectedItem().toString()
and when i try to put a JTextField it works fine.
Sorry for my expression I'm not speak English very well
Thats my code
package guarderia;
import java.awt.BorderLayout;
public class enfermedades extends JFrame {
private JPanel contentPane;
private JTextField txtid;
private JTextField textField_1;
private JTextField txtnom;
private static JTable table;
//VARIABLES PARA CONEXION A MYSQL
static Connection con;
static CallableStatement ps;
static ResultSet rs;
static DefaultTableModel tm;
static Statement sql;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
enfermedades frame = new enfermedades();
frame.setVisible(true);
llenar();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public enfermedades() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1211, 663);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 255, 255));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBackground(new Color(0, 0, 0));
panel.setBounds(0, 0, 1624, 53);
contentPane.add(panel);
JLabel lblEnfermedades = new JLabel("ENFERMEDADES");
lblEnfermedades.setForeground(Color.WHITE);
lblEnfermedades.setFont(new Font("Dialog", Font.BOLD, 19));
lblEnfermedades.setBounds(12, 12, 231, 41);
panel.add(lblEnfermedades);
JPanel panel_1 = new JPanel();
panel_1.setLayout(null);
panel_1.setBounds(10, 102, 426, 510);
contentPane.add(panel_1);
JLabel lblIdNio = new JLabel("ID NiƱo");
lblIdNio.setBounds(12, 30, 70, 15);
panel_1.add(lblIdNio);
txtid = new JTextField();
txtid.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
int c = e.getKeyChar();
if (c < '0' || c > '9') e.consume();
}
#Override
public void keyReleased(KeyEvent e) {
con= (Connection) conexion.conectar();
try {
if (txtid.getText().equals(""))
{
txtnom.setText("");
}
ps = (CallableStatement) con.prepareCall("{call select_nin (?) }");
ps.setLong(1, Integer.parseInt(txtid.getText()));
ResultSet res = ps.executeQuery();
if (res.next())
{
String tipo = res.getString("Nombre");
txtnom.setText(tipo);
llenar();
}
else
{
txtnom.setText(null);
}
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1 );
}
}
});
txtid.setColumns(10);
txtid.setBounds(120, 28, 146, 19);
panel_1.add(txtid);
JLabel cbi = new JLabel("Enfermedad");
cbi.setBounds(12, 95, 194, 15);
panel_1.add(cbi);
JLabel lblTratamiento = new JLabel("Tratamiento");
lblTratamiento.setBounds(12, 130, 194, 15);
panel_1.add(lblTratamiento);
JButton btnNueva = new JButton("Nueva");
btnNueva.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNueva.setBounds(282, 90, 88, 25);
panel_1.add(btnNueva);
JTextPane textPane = new JTextPane();
textPane.setBounds(12, 157, 402, 118);
panel_1.add(textPane);
JLabel lblFechaDeteccion = new JLabel("Fecha Deteccion");
lblFechaDeteccion.setBounds(12, 299, 194, 15);
panel_1.add(lblFechaDeteccion);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(135, 297, 95, 19);
panel_1.add(textField_1);
JLabel lblNombre = new JLabel("Nombre");
lblNombre.setBounds(12, 61, 70, 15);
panel_1.add(lblNombre);
txtnom = new JTextField();
txtnom.setEditable(false);
txtnom.setColumns(10);
txtnom.setBounds(120, 56, 294, 19);
panel_1.add(txtnom);
JLabel lblMedidadRecomendadas = new JLabel("Medidas recomendadas");
lblMedidadRecomendadas.setBounds(12, 330, 194, 15);
panel_1.add(lblMedidadRecomendadas);
JTextPane textPane_1 = new JTextPane();
textPane_1.setBounds(12, 355, 402, 93);
panel_1.add(textPane_1);
JButton btnGuardar = new JButton("Guardar");
btnGuardar.setBounds(297, 470, 117, 25);
panel_1.add(btnGuardar);
JComboBox cbx = new JComboBox();
cbx.setBounds(120, 90, 146, 24);
panel_1.add(cbx);
JPanel panel_2 = new JPanel();
panel_2.setLayout(null);
panel_2.setBackground(new Color(220, 20, 60));
panel_2.setBounds(10, 65, 426, 32);
contentPane.add(panel_2);
JLabel lblRegistrarEnfermedad = new JLabel("Registrar enfermedad");
lblRegistrarEnfermedad.setForeground(Color.WHITE);
lblRegistrarEnfermedad.setFont(new Font("Dialog", Font.BOLD, 19));
lblRegistrarEnfermedad.setBounds(12, 5, 401, 23);
panel_2.add(lblRegistrarEnfermedad);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(448, 102, 751, 510);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JPanel panel_3 = new JPanel();
panel_3.setLayout(null);
panel_3.setBackground(new Color(128, 0, 128));
panel_3.setBounds(448, 65, 751, 32);
contentPane.add(panel_3);
JLabel lblEnfermedades_1 = new JLabel("Enfermedades");
lblEnfermedades_1.setForeground(Color.WHITE);
lblEnfermedades_1.setFont(new Font("Dialog", Font.BOLD, 19));
lblEnfermedades_1.setBounds(12, 5, 401, 23);
panel_3.add(lblEnfermedades_1);
}
public static void llenar()
{
try
{
con = (Connection) conexion.conectar();
String[]titulos={"ID", "ENFERMEDAD", "DESCRIPCION", "RIESGO CONTAGIO", "TIPO"};
String cmd = "select * from enfermedades";
tm = new DefaultTableModel(null,titulos);
sql = (Statement) con.createStatement();
ResultSet rs = sql.executeQuery(cmd);
String[]fila = new String[5];
while(rs.next())
{
fila[0]= rs.getString("id");
fila[1]= rs.getString("enfermedad");
fila[2]= rs.getString("descripcion");
fila[3]= rs.getString("riesgo");
fila[4]= rs.getString("tipo");
tm.addRow(fila);
}
table.setModel(tm);
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(3);
columnModel.getColumn(1).setPreferredWidth(50);
columnModel.getColumn(2).setPreferredWidth(290);
}
catch(Exception d)
{
JOptionPane.showMessageDialog(null, d + " No se pudo conectar.");
}
}
public void ns()
{
cbx. //this is where not recognize the jcombobox
}
}
Your problem appears to be one simply of variable scope. When you declare the cbx variable within your constructor, it is visible only within the constructor. If you move the declaration to the class, then the variable becomes visible throughout the class.
So if you move JComboBox cbx = new JComboBox(); to the class level, in other words if you move this statement to just below your private JTextField txtnom; statement, then the cbx field will be visible within the ns method.
So in other words, make these changes:
public class enfermedades extends JFrame {
private JPanel contentPane;
private JTextField txtid;
private JTextField textField_1;
private JTextField txtnom;
private static JTable table;
// !! added
private JComboBox cbx = new JComboBox();
// ...... code removed for brevity's sake
public enfermedades() {
// ...... code removed for brevity's sake
panel_1.add(btnGuardar);
// !! JComboBox cbx = new JComboBox(); // ***** Don't declare this here ****
// ...... code removed for brevity's sake
}
// ...... code removed for brevity's sake
public void ns() {
// cbx field is now visible here
}
}
Other unrelated problems within your code:
Avoid using null layouts and setBounds. While this might seem to newbies the easiest way to create GUI's, believe me, it's not. Much better to learn how to use the layout managers and use them.
None of the mysql fields or the JTable table field should be static. They should be instance (non-static) fields only. This means that you shouldn't try to access them in a static way.
the llenar method shouldn't be static, and you should call it off of the instance that you've created.
Learn and follow Java naming conventions so that others (we) can better understand your code. Class names begin with an upper-case letter and variable and method names begin with a lower-case letter.
Your sql code should be located in its own class and not within the GUI class's code.
You will want to make sql calls in a separate thread off of the GUI's main event thread, the "EDT".
Making it public magically won't make you access it anywhere from world.
You need to have that instance in order to access that.
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 .
This is my javax.swing class. But it always throws the error java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 2. Not quite sure what is causing it. Where is the error?
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import javax.swing.*;
public class SwingSearchApp extends JFrame implements ActionListener {
//Initializing Components
private static final long serialVersionUID = 1L;
JLabel lb, lb1, lb2, lb3, lb4, lb5;
JTextField tf1, tf2, tf3, tf4, tf5;
JButton btn;
//Creating Constructor for initializing JFrame components
SwingSearchApp() {
//Providing Title
super("Fetching Student Information");
lb5 = new JLabel("Enter Name:");
lb5.setBounds(20, 20, 100, 20);
tf5 = new JTextField(20);
tf5.setBounds(130, 20, 200, 20);
btn = new JButton("Submit");
btn.setBounds(50, 50, 100, 20);
btn.addActionListener(this);
lb = new JLabel("Fetching Search Information From Database");
lb.setBounds(30, 80, 450, 30);
lb.setForeground(Color.red);
lb.setFont(new Font("Serif", Font.BOLD, 20));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
lb1 = new JLabel("U_Name:");
lb1.setBounds(20, 120, 100, 20);
tf1 = new JTextField(50);
tf1.setBounds(130, 120, 200, 20);
lb2 = new JLabel("U_Mail:");
lb2.setBounds(20, 150, 100, 20);
tf2 = new JTextField(100);
tf2.setBounds(130, 150, 200, 20);
lb3 = new JLabel("U_Pass:");
lb3.setBounds(20, 180, 100, 20);
tf3 = new JTextField(50);
tf3.setBounds(130, 180, 200, 20);
lb4 = new JLabel("U_Country:");
lb4.setBounds(20, 210, 100, 20);
tf4 = new JTextField(50);
tf4.setBounds(130, 210, 100, 20);
setLayout(null);
//Add components to the JFrame
add(lb5);
add(tf5);
add(btn);
add(lb);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
add(lb4);
add(tf4);
//Set TextField Editable False
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
tf4.setEditable(false);
}
public void actionPerformed(ActionEvent e) {
//Create DataBase Coonection and Fetching Records
try {
String str = tf5.getText();
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\employee.accdb";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, "", "");
//Connection con = DriverManager.getConnection("jdbc:oracle:thin:#mcndesktop07:1521", "sandeep", "welcome");
PreparedStatement st = con.prepareStatement("select * from emp where uname=?");
st.setString(1, str);
//Excuting Query
ResultSet rs = st.executeQuery();
if (rs.next()) {
String s = rs.getString(1);
String s1 = rs.getString(2);
String s2 = rs.getString(3);
String s3 = rs.getString(4);
//Sets Records in TextFields.
tf1.setText(s);
tf2.setText(s1);
tf3.setText(s2);
tf4.setText(s3);
} else {
JOptionPane.showMessageDialog(null, "Name not Found");
}
//Create Exception Handler
} catch (Exception ex) {
System.out.println(ex);
}
}
//Running Constructor
public static void main(String args[]) {
new SwingSearchApp();
}
}
The structure of my table in Access database contains the following fields:-
uname, umail, upass, upcountry.
This can happen if uname doesn't exist in your table. Check the spelling/case.
Reference: here
Update:
Try to modify your code a little to be able to just run a simple query and get a result set. This will then allow you to query for the column names as your driver sees them:
ResultSet rs = stmt.executeQuery("SELECT * FROM emp");
ResultSetMetaData rsmd = rs.getMetaData();
String firstColumnName = rsmd.getColumnName(1);
// etc..
That will tell you for sure.
I am trying to create a register system for my MySQL database. I have a Java form that I created, in which the user inserts a username, password, and their email. I take that infromation and store it in a variable accordingly. The MySQL connection code works, and it does insert a new row, but the information is blank on the MySQL page. Am I doing someting wrong?
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JPasswordField passwordField;
private static Connection con;
private static PreparedStatement st;
private static int rs;
String username;
String password;
String email;
private JTextField textField_1;
String insertTableSQL = "INSERT INTO `users`" + "(username, password, email) VALUES" + "(?,?,?)";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
setResizable(false);
setTitle("Barrage : Login / Register");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 350, 200);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Username: ");
lblNewLabel.setBounds(60, 25, 68, 20);
contentPane.add(lblNewLabel);
JLabel lblPassword = new JLabel("Password: ");
lblPassword.setBounds(60, 59, 68, 20);
contentPane.add(lblPassword);
textField = new JTextField();
username = textField.getText();
textField.setBounds(138, 22, 120, 26);
contentPane.add(textField);
textField.setColumns(10);
passwordField = new JPasswordField();
password = passwordField.getText();
passwordField.setBounds(138, 56, 120, 26);
contentPane.add(passwordField);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/barrage", "root", "");
st = con.prepareStatement(insertTableSQL);
st.setString(1, username);
st.setString(2, password);
st.setString(3, email);
st.executeUpdate();
} catch(Exception e) {
e.printStackTrace();
}
}
});
btnRegister.setBounds(119, 138, 89, 23);
contentPane.add(btnRegister);
JLabel lblEmail = new JLabel("E-mail: ");
lblEmail.setBounds(60, 96, 68, 20);
contentPane.add(lblEmail);
textField_1 = new JTextField();
email = textField_1.getText();
textField_1.setBounds(138, 93, 120, 26);
contentPane.add(textField_1);
textField_1.setColumns(10);
}
}
You need to call the various fields' getText() method in your ActionListener so that you get the values after the user has entered them.
As it stands now you get the initial values prior to any user interaction.
You need to set the values of username u.a. in the moment where you you call the actionPerformed method.
Right now you set the value when creating the GUI. At that moment they are null. They are not "linked", they just take the value that the controls return at that time. If the controls getText() result changes, your variables do not get updated.