Adding component to JTable - java

I want to add JButton in table. I am using table to display database records. Actually I want to add button for each record in table but, the button is not displayed on table. It doesnt show any errors. Please help. Thanks in advance.
package addPanel;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class panelShowData extends JPanel
{
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
String url = "jdbc:mysql://localhost:3306/records";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
JScrollPane scrollPane;
JTable table;
DefaultTableModel tableModel;
String nameSearch="";
public panelShowData()
{
this.setLayout(null);
setVisible(true);
setBounds(0, 200, 500, 450);
}
public void searchData( String nameSearch)
{
tableModel = new DefaultTableModel();
try
{
Class.forName( driver ).newInstance( );
connection = DriverManager.getConnection( url, userName, password );
statement = connection.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE );
resultSet = statement.executeQuery( "select * from registration where firstname='"
+ nameSearch
+ "'or lastname ='"
+ nameSearch + "'" );
System.out.println( "Query executed" );
System.out.println( "nameSearch="+nameSearch );
String firstName;
String lastName;
int id;
JButton add=new JButton("ADD");
while ( resultSet.next( ) )
{
System.out.print( resultSet.getString( 2 ) + "\t" );
System.out.print( resultSet.getString( 4 ) + "\n" );
firstName = resultSet.getString( 2 );
lastName = resultSet.getString( 4 );
id = resultSet.getInt(1);
String[ ] columnName = { "Id","First Name", "Last Name","click" };
Object[ ] data = { id, ""+firstName, "" + lastName, add };
System.out.println("Names is:"+firstName);
tableModel.setColumnIdentifiers( columnName );
tableModel.addRow( data );
tableModel.fireTableDataChanged();
}
table = new JTable( tableModel );
table.setEnabled(false);
scrollPane = new JScrollPane( table );
scrollPane.setBounds( 10, 10, 350, 100 );
scrollPane.revalidate();
scrollPane.repaint();
add( scrollPane );
connection.close( );
}
catch (Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog( null, "Record Not Found",
"Sorry", JOptionPane.ERROR_MESSAGE );
}
}
}

all code lines in your post are important reasons, why ResultSetTableModel, TableFromDatabase (and/or to invoked JDBC from SwingWorker, Runnable#Thread) are there
never to call tableModel.fireTableDataChanged();,
outside XxxTableModel defintion
DefaultTableModel has implemented this notifier and correctly
your code required to override this notifiers because talking about Concurency in Swing (Oracle tutorial), again about my point 1st.
everything important is there, please to read this answer about ListModel and JList, all points, the same issue,
JPanel has FlowLayout implemented in API, no reason to use NullLayout, change that to BorderLayout
override getPreferredSize for reasonable Dimension for JPanel, contains JTable wrapped in JScrollPane
JButton added in JTable is here solved a few times

Related

Reset JTable depending on content (number of rows)

I have a JTable inside a JPanel which in turn is in a Jframe. The JTable loads users from a table (database in MySQL).
I have a search engine using DNIs in which key-to-key, with a KeyTyped event, is updating the contacts in the table, and show only those that meet the browser pattern (JTextField). If there are only 2-3-4 clients, the table is not resized to the customer size, but fills the rest of the table with a gray background. (see image). How could the lower bound of the table be reset?
Code:
public class Listado_clientes1 extends javax.swing.JFrame{
private TableRowSorter<DefaultTableModel> TRSFiltro;
public Listado_clientes1() {
this.getContentPane().setBackground(Color.orange);
panel_top.setBackground(Color.orange);
tabla_clientes.setPreferredScrollableViewportSize(
new Dimension(tabla_clientes.getPreferredSize().width, tabla_clientes.getRowHeight()*20)
);
try {
DefaultTableModel modelo = new DefaultTableModel();
tabla_clientes.setModel(modelo);
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = Conexiones.conexion_a_BBDD("agenda");
String sql = "SELECT dni, nombre, apellidos, telefono, direccion, ciudad, email FROM clientes";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData rsMd = (ResultSetMetaData) rs.getMetaData();
int cantidadColumnas = rsMd.getColumnCount();
modelo.addColumn("DNI");
modelo.addColumn("NOMBRE");
modelo.addColumn("APELLIDOS");
modelo.addColumn("TLFONO");
modelo.addColumn("DIRECCION");
modelo.addColumn("CIUDAD");
modelo.addColumn("EMAIL");
while (rs.next()) {
Object[] filas = new Object[cantidadColumnas];
for (int i=0; i<cantidadColumnas; i++) {
filas[i] = rs.getObject(i+1);
}
modelo.addRow(filas);
}
} catch (SQLException ex) {
System.err.println(ex.toString());
}
}
/**
* Filtrar: Buscar por DNI.
*/
public void filtrar_dni() {
int columna = 0; //Es la fila del DNI.
TRSFiltro.setRowFilter(RowFilter.regexFilter(textfield_buscar.getText(), columna));
}
private void textfield_buscarKeyTyped(java.awt.event.KeyEvent evt) {
Character letra = evt.getKeyChar();
evt.setKeyChar(Character.toUpperCase(letra));
textfield_buscar.addKeyListener(new KeyAdapter(){
public void keyReleased(final KeyEvent e){
String texto = (textfield_buscar.getText());
textfield_buscar.setText(texto);
filtrar_dni();
}
});
TRSFiltro = new TableRowSorter<DefaultTableModel>((DefaultTableModel) tabla_clientes.getModel());
tabla_clientes.setRowSorter(TRSFiltro);
}
}
Outline / Scheme:
Any time the number of rows in the view of the table changes you need to recalculate the
preferred scrollable viewport size of the table. Once this size is recalculated you need to invoke the layout manager of the panel containing the table:
A reusable method would be something like:
public void resetTablePreferredScrollableViewportSize(JTable table, int maxRows)
{
Dimension size = table.getPreferredSize();
int displayRows = Math.min(table.getRowCount(), maxRows);
size.height = displayRows * table.getRowHeight();
table.setPreferredScrollableViewportSize( size );
Container parent = SwingUtilities.getAncestorOfClass(JPanel.class, table);
parent.revalidate();
parent.repaint();
}
So after setting the row filter you could use:
tabla_clientes.setRowSorter(TRSFiltro);
resetTablePreferredScrollableViewportSize(tabla_clientes, 10);
Now the scroll pane should be sized to display up to 10 rows after which the scrollbar of the scroll pane will appear.
Edit:
I don't know how to put a reproducible example
Then you don't understand what your problem is.
Your question is that you want to:
Reset JTable (size) depending on number of rows
So the data is irrelevant, only the number of rows is relevant.
It is easy to test this because you can create a DefaultTableModel with a specified number of rows.
Below is a simple MRE. To test you:
enter a number in the text field
press enter
The table will be resized to display the specified number of rows. If the number is greater that 10 the table size will be fixed and a scrollbar will appear:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
JTextField textField;
JTable table;
public SSCCE()
{
setBackground(Color.YELLOW);
textField = new JTextField(5);
add(textField);
table = new JTable(new DefaultTableModel(0, 4));
table.setPreferredScrollableViewportSize(table.getPreferredSize());
add( new JScrollPane(table) );
textField.addActionListener((e) ->
{
int rows = Integer.parseInt( textField.getText() );
table.setModel( new DefaultTableModel(rows, 4) );
resetTablePreferredScrollableViewportSize(table, 10);
});
}
public void resetTablePreferredScrollableViewportSize(JTable table, int maxRows)
{
Dimension size = table.getPreferredSize();
int displayRows = Math.min(table.getRowCount(), maxRows);
size.height = displayRows * table.getRowHeight();
table.setPreferredScrollableViewportSize( size );
Container parent = SwingUtilities.getAncestorOfClass(JPanel.class, table);
parent.revalidate();
parent.repaint();
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// frame.pack();
frame.setSize(500, 250);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}

Login issue in java swing

I want to create a login page but it's not working properly. When I type in a username and password and click on the Login button, nothing is happening and I am not seeing any error message.
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
public class acclogin extends JFrame {
Connection con;
Statement st;
ImageIcon bg = new ImageIcon("wb1.jpg");
JFrame f = new JFrame("User Login");
ResultSet rs;
JLabel l = new JLabel("Username");
JLabel l1 = new JLabel("Password");
JLabel l2 = new JLabel(bg);
JTextField t = new JTextField(15);
JPasswordField t1 = new JPasswordField(15);
JButton b = new JButton("Login");
public acclogin() {
frame();
}
public void frame() {
f.setSize(620, 300);
l.setBounds(10, 20, 100, 10);
t.setBounds(100, 20, 100, 20);
l1.setBounds(10, 50, 100, 80);
t1.setBounds(100, 70, 100, 20);
b.setBounds(100, 130, 100, 30);
l2.setBounds(0, 0, 600, 300);
f.add(l);
f.add(t);
f.add(l1);
f.add(t1);
f.add(b);
f.add(l2);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
LoginButton lb = new LoginButton();
b.addActionListener(lb);
}
class LoginButton implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj == b) {
try {
String user = t.getText().trim();
String pass = t1.getText().trim();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 = DriverManager.getConnection("jdbc:odbc:balogin");
Statement stat;
stat = con1.createStatement();
ResultSet rs = stat.executeQuery("select * from Table1 where user='" + user + "' and pass='" + pass + "'");
System.out.println("select * from Table1 where user='" + user + "' and pass='" + pass + "'");
int count = 0;
while (rs.next()) {
{
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "User Found,Access Granted");
ControlPanel cp1 = new ControlPanel();
cp1.display();
} else {
JOptionPane.showMessageDialog(null, "User not found");
}
}
} catch (Exception ex) {
}
}
}
}
public static void main(String args[]) {
new acclogin();
}
}
This is not exactly a solution for the problem, but this code has so many issues that you should solve before moving on.
This is what I would do:
split the code into multiple methods to take apart UI code from working with database
do not concat SQL query from strings, use prepared statement instead (omiting this could lead to an SQL injection, try login as ';DROP TABLE user;--)
usage of int count just for checking an existence of an element is confusing, you can use boolean or change SQL query to SELECT COUNT(*) ... or SELECT 1 IF EXISTS (SELECT * FROM ...)
you do not have to check the action event source, it will be always be the login button unless you assign the listener to something else
add e.printStackTrace() on catching exception
I also believe that you should use JPasswordTextField.getPassword() instead of getText()
remember closing ResultSet and Statement after use by calling .close()
try this :
Object obj = ae.getSource();
if ((JButton)obj ==(JButton)b) {
......... }

Sqlite data and Auto created buttons on ScrollPane [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to do something a bit awkward.
I want to check if there in data in my Sqlite database and according to the number of tables, I want to create buttons in a scroll pane and make it responsive. This is just java "JDBC" not android. I know you guys will tell me to show what i've tried, but I have no idea at all.
Thank you in advance.
Maybe this will get you started.
This code should display the tables from the database in a combo box. Then when you select a table from the combo box is should display all the column in the table.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class DatabaseInformation extends JFrame implements ActionListener
{
DatabaseMetaData dmd;
ResultSet rs;
ResultSetMetaData md;
int columns;
JComboBox comboBox;
JTable table;
String catalog;
public DatabaseInformation()
{
comboBox = new JComboBox();
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
// Connect to the Database
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
// String url = "jdbc:odbc:Teenergy"; // if using ODBC Data Source name
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/teenergy/data/teenergy.mdb";
String userid = "";
String password = "";
Class.forName( driver );
Connection connection = DriverManager.getConnection( url, userid, password );
dmd = connection.getMetaData();
// Get the first Catalog
// Note: the result set can contain multiple catalogs, just look at the first one
rs = dmd.getCatalogs();
if (rs.next())
{
catalog = rs.getObject(1).toString();
System.out.println( catalog );
}
rs.close();
// Get Tables
rs = dmd.getTables(catalog, null, null, new String[] { "TABLE" });
md = rs.getMetaData();
columns = md.getColumnCount();
while (rs.next())
{
comboBox.addItem( rs.getObject(3) );
}
rs.close();
}
catch(Exception e)
{
System.out.println( e );
}
comboBox.addActionListener( this );
getContentPane().add(comboBox, BorderLayout.NORTH);
// Create table with database data
table = new JTable();
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
}
public void actionPerformed(ActionEvent e)
{
String table = (String)comboBox.getSelectedItem();
displayTableColumns( table );
}
private void displayTableColumns(String tableName)
{
try
{
// Get Columns
rs = dmd.getColumns(catalog, null, tableName, null);
md = rs.getMetaData();
int columns = md.getColumnCount();
Vector columnNames = new Vector(columns);
Vector data = new Vector();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
// Reset Table
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table.setModel( model );
}
catch(Exception e)
{
System.out.println( e );
}
}
public static void main(String[] args)
{
DatabaseInformation frame = new DatabaseInformation();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
I have only ever tested the code on an Access database so I'm not sure what you will need to change for SQLite.

embed MS Access database with runnable jar

So my aim is to make a runnable jar. I've made a program using swings which uses MS Access database to fetch records. So, I've used an absolute path to refer to the database for connection.
Now, I intend to distribute this runnable jar to other people as well. So I guess the best option would be to embed the MS Access database as well in the jar file. But I don't know how to do that. Where should I keep the database in my Project Explorer ? Should I use a relative path etc. Any form of help would be appreciable.
I've found many tutorials for using Derby database that would implement the same but none pertaining to Ms Access database. Suggestions are welcome !
This is my code:-
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class r_search 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;
r_search() {
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 {
Vector v = new Vector();
String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(url,"","");
/*con = DriverManager.getConnection("jdbc:oracle:thin:#mcndesktop07:1521:xe", "sandeep", "welcome");*/
st = con.createStatement();
rs = st.executeQuery("select index_name from Index1");
// Vector v = new Vector();
while (rs.next()) {
ids = rs.getString(1);
v.add(ids);
}
c1 = new JComboBox(v);
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.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
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 textvalue = textbox.getText();
String uname = "";
String email = "";
String pass = "";
String cou = "";
try {
/* pst = con.prepareStatement("select * from emp where UNAME='" + from + "'");*/
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()) {
uname = rs.getString("Section_Name");
email = rs.getString("Report_Name");
pass = rs.getString("Contact_Name");
cou = rs.getString("Link");
model.addRow(new Object[]{uname, email, pass, cou});
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();
}
}
The following worked for me using Eclipse and JavaSE-1.7. Eclipse shows the following in its Package Explorer
The [folders] and files in my project folder are
[C:]
[Users]
[Gord]
[workspace]
[com.example.jartest]
[src]
[com]
[example]
[jartest]
JarTestMain.java
[resources]
JarData.mdb
The Java code in JarTestMain.java is
package com.example.jartest;
import java.io.*;
import java.nio.file.*;
import java.sql.*;
public class JarTestMain {
public static void main(String[] args) {
String mdbFileName = "JarData.mdb";
String tempDbPath = System.getenv("TEMP").replace('\\', '/') + "/" + mdbFileName;
// retrieve .mdb database from the JAR file and save to %TEMP% folder
InputStream strmIn = JarTestMain.class.getResourceAsStream("resources/" + mdbFileName);
File f = new File(tempDbPath);
try {
Files.copy(strmIn, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
// open the copy of the database in %TEMP% folder and read from its table
String connectionString =
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};" +
"DBQ=" + tempDbPath;
try (Connection con = DriverManager.getConnection(connectionString)) {
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM Table1");
while (rs.next()) {
System.out.println(String.format(
"%d: %s",
rs.getInt("ID"),
rs.getString("TextField")));
}
rs.close();
con.close();
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
After I exported the project to a "Runnable JAR file" named JarTest.jar I was able to run it on my 32-bit Windows test machine using...
"C:\Program Files\Java\jre7\bin\java" -jar JarTest.jar
...and on my 64-bit Windows development machine via
"C:\Program Files (x86)\Java\jre7\bin\java" -jar JarTest.jar

how to retrieve data from db automatic of given id?

Hi i am using swing for data retrieving i i am able to retrieve data on action perform.
but i want to retrieve data when i run this program automatic given id data retrieve from
database.
Help me Please
Thanks
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.*;
public class BankGui extends JApplet implements ActionListener{
// GUI components
JLabel lblUser, lblPass,lblnull,lbl1;
JTextField txtid;
JTextField txtUser;
JTextField txtPass;
JButton btnOk, btnClear;
// connections to MYSQL
private static Connection connection = null;
private static Statement statement = null;
private static ResultSet resultSet = null;
//public static Scanner in = new Scanner(System.in);
public void init(){
Container c = getContentPane();
c.setLayout( new FlowLayout() );
lblUser = new JLabel( "Username: " );
c.add( lblUser );
txtUser = new JTextField( 10 );
c.add( txtUser );
lblPass = new JLabel( "Password:" );
c.add( lblPass );
txtPass = new JTextField( 10 );
c.add( txtPass );
lbl1 = new JLabel( "Enter id" );
c.add( lbl1);
txtid=new JTextField(10);
c.add(txtid);
btnOk = new JButton( "OK" );
btnOk.addActionListener( this );
c.add( btnOk );
lblnull= new JLabel("");
c.add(lblnull);
}
#Override
public void actionPerformed(ActionEvent e) {
PreparedStatement stmt=null;
boolean isFound=false;
try{
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "");
// String sql="SELECT uname FROM users1 WHERE uname=? and pwd=?";
String sql = "SELECT * FROM users WHERE uid = '"+2+"'";
stmt=connection.prepareStatement(sql);
//stmt.getString(1,txtUser.getText());
// stmt.setString(2,txtPass.getText());
resultSet=stmt.executeQuery();
if(resultSet.next()){
isFound=true;
// String s=resultSet.getString(1);
// String s1=resultSet.getString(2);
//System.out.println(s);
txtPass.setText(resultSet.getString(1));
lblnull.setText(resultSet.getString(2));
// System.out.println(s1);
}
//
}catch(SQLException ex){
System.err.println(ex);
}finally{
if(stmt!=null){
try{
stmt.close();
}catch(Exception ex) { /* */ }
}
if(connection!=null){
try{
connection.close();
}catch(Exception ex) { /* */ }
}
}
}
static {
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception ex) {
System.err.println(ex);
}
}
}
If datatype of uid is int then your query should be
String sql = "SELECT * FROM users WHERE uid = "+2;
'2' is used for varchar datatype
In addition to #AJ answer I have some tips:
Database calls are time consuming tasks and may block the Event Dispatch Thread (a.k.a. EDT) causing the GUI become unresponsive. To avoid this issue consider use a SwingWorker to perform database calls in a background thread and update Swing components in the EDT. See more in Concurrency in Swing trail.
It's not a good practice ignore exceptions in a catch block: catch(Exception ex){}
Note your query is vulnerable to SQL injection attaks. To avoid this you may want to try PreparedStatement instead.
Example:
String sql = "SELECT * FROM users WHERE uid = ?";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setInt(1, 2); // see PreparedStatement.setInt(index, value)
ResultSet rs = pst.executeQuery();

Categories