How do I insert Java variables into query through textfields? - java

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.

Related

Jcombobox not selecting item

Im trying to insert the Jcombobox value into my sqlite database but whenever I run the program, it only inserts '9' in to my database. Please advise. I am trying to import the integer that the user picks into my sqlite database. For some reason, even with the action listener, the default value, 9, is still being inputed into the table and im not sure why. Here is the full code, not including the connection and the Jtable.
public class create extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
create frame = new create();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connect = null;
private JTextField textField_2;
String uniqueString = UUID.randomUUID().toString();
private JTextField textField_3;
/**
* Create the frame.
*/
public create() {
connect = connection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBackground(new Color(204, 204, 204));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblStudentName = new JLabel("Student ID:");
lblStudentName.setBounds(96, 69, 72, 16);
contentPane.add(lblStudentName);
textField = new JTextField();
textField.setBounds(173, 64, 216, 26);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblGrade = new JLabel("Grade:");
lblGrade.setBounds(125, 107, 47, 16);
contentPane.add(lblGrade);
JComboBox comboBox = new JComboBox();
comboBox.addItem(9);
comboBox.addItem(10);
comboBox.addItem(11);
comboBox.addItem(12);
comboBox.setBounds(173, 102, 72, 29);
contentPane.add(comboBox);
comboBox.setSelectedItem(9);
comboBox.addActionListener(comboBox);
int selectedNumber = (int)comboBox.getSelectedItem();
JLabel lblInputBookOver = new JLabel("Teacher:");
lblInputBookOver.setBounds(111, 146, 61, 21);
contentPane.add(lblInputBookOver);
textField_1 = new JTextField();
textField_1.setBounds(173, 143, 216, 26);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton button = new JButton("<");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int count = 0; count <= 0; count++) {
//dispose();
options sc = new options();
sc.setVisible(true);
}
}
});
button.setBounds(6, 6, 30, 29);
contentPane.add(button);
JLabel lblStudentname = new JLabel("Student Name:");
lblStudentname.setBounds(74, 31, 99, 16);
contentPane.add(lblStudentname);
textField_2 = new JTextField();
textField_2.setBounds(173, 26, 216, 26);
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(125, 180, 42, 26);
contentPane.add(lblEmail);
textField_3 = new JTextField();
textField_3.setBounds(173, 180, 216, 26);
contentPane.add(textField_3);
textField_3.setColumns(10);
JButton btnCheckout = new JButton("Checkout");
btnCheckout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String uniqueString = UUID.randomUUID().toString().replace("-", "");
try {
String query = "insert into data ('Name', 'Student ID', 'Teacher', 'Grade', 'Email', 'Ebook') values (?,?,?,?,?,?)";
PreparedStatement pst = connect.prepareStatement(query);
pst.setString(1,textField_2.getText() );
pst.setString(2,textField.getText() );
pst.setString(3,textField_1.getText() );
pst.setInt(4, selectedNumber);
pst.setString(5,textField_3.getText() );
pst.setString(6, uniqueString);
for (int count = 0; count <= 0; count++) {
//dispose();
confirm sc = new confirm();
sc.setVisible(true);
count = 0;
}
pst.execute();
pst.close();
}
catch (Exception w){
w.printStackTrace();
}
}
});
btnCheckout.setBounds(173, 218, 117, 29);
contentPane.add(btnCheckout);
}
}
It inserts 9 to your database because the selected item is always 9, and this because you add it first to your combobox. In order to insert the selected value, you will have to use an ActionListener. Then you can take user's selection and do whatever you want.
An example of its usage:
import java.awt.FlowLayout;
import java.io.FileNotFoundException;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class ComboBox extends JFrame {
public ComboBox() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
getContentPane().setLayout(new FlowLayout());
Integer[] numbers = { 4, 5, 8, 123, 42, 634 };
JComboBox<Integer> comboBox = new JComboBox<>(numbers);
comboBox.setSelectedItem(42); // The initial selection is 42.
comboBox.addActionListener(e -> {
int selectedNumber = (int) comboBox.getSelectedItem();
System.out.println("Selected number: " + selectedNumber);
// Do whatever with selected number
});
add(comboBox);
}
public static void main(String[] args) throws FileNotFoundException {
SwingUtilities.invokeLater(() -> new ComboBox().setVisible(true));
}
}

JComboBox in a public class

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.

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 .

Java Insert Data Display on Console IDE

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

Runnable jar connects to sqlite but exe of the same doesn't

I have created a runnable jar file for a login page. The folder where the runnable jar is saved also contains a folder named "lib" which contains files for images (used for icons and stuff) and an sqlite database file (which contains usernames and passwords).
When I execute the runnable jar and click on the login button after entering the username and password, it successfully executes. But when I convert the same jar file to exe and run it, the images from lib folder get loaded, but nothing happens when I click the login button. It seems as if the exe file is not connecting to the sqlite database in the "lib" folder.
Following is the code:
package db;
import javax.swing.*;
public class One extends JFrame {
private JButton btn_login = new JButton("LOGIN");
private JPanel panel = new JPanel();
private JTextField tf_user;
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs= null;
private JPasswordField tf_pass;
public static void main(String[] args) {
One frameTabel = new One();
}
One(){
super("LOGIN PAGE");
setTitle("NETWORK TRACKER - LOGIN");
setBackground(new Color(70, 130, 180));
btn_login.setFont(new Font("Tahoma", Font.PLAIN, 8));
btn_login.setBackground(new Color(102, 205, 170));
btn_login.setForeground(Color.WHITE);
btn_login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:lib/login.sqlite");
String sql = "SELECT * from table12 where Username=? and Password=?";
pst = conn.prepareStatement(sql);
pst.setString(1, tf_user.getText());
pst.setString(2, tf_pass.getText());
rs = pst.executeQuery();
if(rs.next()){
rs.close();
pst.close();
setVisible(false);
Display dp = new Display();
dp.setVisible(true);
dp.setSize(300, 300);
} else{
JOptionPane.showMessageDialog(null, "Username or Password is not correct");
}
} catch (Exception e){
System.out.println("Error: "+e);
} finally{
try{
rs.close();
pst.close();
} catch (Exception e){
}
}
}
});
btn_login.setBounds(342,153,58,20);
panel.setBackground(new Color(112, 128, 144));
panel.add(btn_login);
setupLog();
getContentPane().add(panel);
JLabel lbl_title = new JLabel("NETWORK TRACKER LOGIN PAGE ");
lbl_title.setBackground(new Color(47, 79, 79));
lbl_title.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_title.setForeground(Color.LIGHT_GRAY);
lbl_title.setFont(new Font("HelveticaNeue", Font.PLAIN, 16));
lbl_title.setBounds(0, 252, 457, 23);
panel.add(lbl_title);
JLabel lbl_user = new JLabel("USERNAME");
lbl_user.setFont(new Font("HelveticaNeue", Font.PLAIN, 12));
lbl_user.setForeground(new Color(255, 250, 250));
lbl_user.setBounds(263, 93, 69, 14);
panel.add(lbl_user);
tf_user = new JTextField();
tf_user.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
tf_user.setBounds(342, 90, 105, 22);
panel.add(tf_user);
tf_user.setColumns(10);
JLabel lbl_pass = new JLabel("PASSWORD");
lbl_pass.setFont(new Font("HelveticaNeue", Font.PLAIN, 12));
lbl_pass.setForeground(new Color(255, 250, 250));
lbl_pass.setBounds(263, 129, 69, 14);
panel.add(lbl_pass);
tf_pass = new JPasswordField();
tf_pass.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
tf_pass.setBounds(342, 123, 105, 20);
panel.add(tf_pass);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon("lib/login.png"));
label.setBounds(0, 11, 236, 240);
panel.add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void setupLog(){
setSize(473,313);
setLocation(500,280);
panel.setLayout (null);
}
}

Categories

Resources