Filtering MySQL data to JTable - java

I have a table in my SQL in the following structure called student:
+-----------+-----------+-----------+------------+
| studentno | lastname | firstname | middlename |
+-----------+-----------+-----------+------------+
| 2001-0001 | Matrix | John | G |
| 2001-0002 | Mata | Evan | A |
| 2001-0003 | Melly | Carmelo | P |
| 2001-0004 | Hamburger | Hardy | P |
+-----------+-----------+-----------+------------+
I have a JTable and a JTextField in my Java Program. What I would like to do is, if I type letter M (case insensitive) in the JTextField, all the student who's last name starts with letter M will display on my JTable. If I type a second letter, say for example, A, all the students who's last name starts with MA will display, until I got a specific last name on my JTable..
My problem is that, even though I type letter M, all of the data in my MAappears on my JTable instead of just all the students who's last name starts with letter M..
And my JTable doesn't clears up even if I empty my JTextField..
I am using Netbeans and so far I have this code in my JTextFieldKeyPressed:
private void lastNameKeyPressed(java.awt.event.KeyEvent evt) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "students_dbs";
Statement stmt = null;
ResultSet result = null;
String driver = "com.mysql.jdbc.Driver";
String databaseUserName = "user1";
String databasePassword = "test";
PreparedStatement pst = null;
try{
conn = DriverManager.getConnection(url + dbName, databaseUserName, databasePassword);
stmt = conn.createStatement();
System.out.println("Connected to the database.");
}catch(Exception e){
System.out.println("Failed to connect ot the database.");
}
try{
String sql = "SELECT studentno, lastname, firstname, middlename FROM student WHERE lastname LIKE '%" + lastname.getText() + "%'";
pst = conn.prepareStatement(sql);
result = pst.executeQuery();
studentsTable.setModel(DbUtils.resultSetToTableModel(result));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}

First you need to add a listener to Listen for changes in the text, then send that text to your query to retrieve new data based on the passed text.
// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warm();
}
public void warn() {
// fire the execute statement.
}
});
then you need to change your query to something like this:
String sql = "SELECT studentno, lastname, firstname, middlename FROM student WHERE firstname= '" + jtextfield.getText() + "%'";

Related

JDBC MySql driver returns wrong value after working for a long time

I have a MySQL db and I have an issue with two tables named product and product_older. They have same structure and product table's rows copied into product_older for once in a day. Here is their structure:
+-----------------------+---------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------+---------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| price | decimal(18,2) | YES | | NULL | |
| price_older | decimal(18,2) | YES | | NULL | |
+-----------------------+---------------+------+-----+-------------------+----------------+
I have problem with only price_older field. My program updates values of product table for over 3 million data. price_older field takes it value from price column of product_older every time.
Here is the method which I take price_older:
private double getOlderPrice(int id) {
double price_older = 0.0d;
try {
String query = tools.getQuery("select price from product_older where id=?")
.replace("?", String.valueOf(id));
com.mysql.jdbc.Connection connection = (Connection) DriverManager.getConnection(db_url, username, password);
preparedStatement = (PreparedStatement) connection.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
price_older = resultSet.getDouble(1);
}
} catch (SQLException e) {
..... // error log
} finally {
.... //close the prepared statement
}
return price_older;
}
And I use that price_older value to create PriceList object for every product then I used that list to update product table. Here is my update code:
(Same connection object used in here with the getOlderPrice method.)
private void dbUpdate() throws SQLException {
String query = "update product set price=?, price_older=? where id=?";
try (com.mysql.jdbc.Statement statement = (Statement) connection.createStatement();
com.mysql.jdbc.PreparedStatement updateStatement = (PreparedStatement) connection.prepareStatement(query)) {
connection.setAutoCommit(false);
int batchIndex = 0;
for (UpdatePrice price : priceList) {
if (price.getPrice() == null) {
updateStatement.setNull(1, Types.DECIMAL);
} else {
updateStatement.setDouble(1, price.getPrice());
}
updateStatement.setDouble(2, price.getOlderPrice());
updateStatement.setInt(3, price.getID());
updateStatement.addBatch();
batchIndex++;
if (batchIndex % limitedBatchSize == 0) {
updateStatement.executeBatch();
connection.commit();
}
}
updateStatement.executeBatch();
connection.commit();
connection.setAutoCommit(true);
priceList.clear();
}
}
Here is the problem; It works fine for most of the time but about once every ~30 days it updates older_price with the wrong value and that wrong value is usually belong to another product in the db and when it updates the column with the wrong value there is no error in the log because it appears OK.
And my connection's rewriteBatchedStatements is set to true.
How could that be? If there is a bug, why it works fine most of the time and how there is no problem with the price column? If there is not why it updates a value in the wrong place?
I have been searched for over a week now but there is no result and also I can not reproduce the bug and it makes less possible to be sure where is the problem actually.

java.sql.SQLException: Column Index out of range

i need a help when i execute the following MYSQL command in Navicat i get
mysql> SELECT Password FROM workers;
+----------+
| Password |
+----------+
| A |
| B |
| B |
| B |
| B |
when i fire it in java i get
java.sql.SQLException: Column Index out of range, 3 > 2.
Code :-
try {
ArrayList<String> A = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "123456");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Password FROM workers");
int c =1;
while(rs.next())
{
A.add(rs.getString(c));
c++;
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
Since you are only getting 1 column, you are out of range. You change your code as follows, and remove your counter.
try {
ArrayList<String> A = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "123456");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Password FROM workers");
while(rs.next())
{
A.add(rs.getString("Password"));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
You have 5 entries in your database table and execute the following code:
int c = 1;
while (rs.next()) {
A.add(rs.getString(c)); // get value at column
c++;
}
1st iteration: rs.getString(1), get value at column 1
2nd iteration: rs.getString(2), get value at column 2
and so on
Now, your table only has one column, therefore you should access your value with either
rs.getString(int column), here always 1
rs.getString(String columnLabel), here Password

update different column values with specific value

a table has a column named 'score' with different values.
| name | contact | area | score |
| james | +222451 | eastp|70 |
| jimmy | +222451 | eestp | 80 |
| k.josh | +222451 | ecstp | 50 |
| L.john | +222451 | efstp | 60 |
I want to update all score values with a specific value. eg. update all score values with 10.
therefore value 70 will be 80
value 80 will be 90
value 50 will be 60
value 60 will be 70
please how do I write a code to achieve this. wrote down this but all columns get changed to the same value. please help.
int reg = 10;
try {
String sql1 = "select Score from db_table where ID=db_table.ID";
pst = con.prepareStatement(sql1);
rs = pst.executeQuery();
while(rs.next())
{
int ad = rs.getInteger("Score");
int fad = ad+reg;
String sql2 = "update db_table set Score='" + fad + "' where _ID=db_table.ID";
pst = con.prepareStatement(sql2);
pst.execute();
}
} catch(SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(null,e);
} finally
{
try
{
rs.close();
pst.close();
} catch(Exception e)
{}
}
but anytime is executed, the whole column values are replaced with the same value '10'. instead of each column value should rather be increased by 10. please help
Use the following query:
UPDATE db_table
SET score = score + 10
So, basically you don't need to SELECT all the scores first, and then manipulate them inside Java code, and use UPDATE one by one. Instead, change your try block in the Java code as follows:
try
{
String sql1 = "UPDATE db_table Set score = score + " + String.valueOf(reg);
pst = con.prepareStatement(sql1);
rs = pst.executeQuery();
}
Try this:
int reg = 10;
try{
String sql1="select Score from db_table where ID=db_table.ID";
pst=con.prepareStatement(sql1);
rs=pst.executeQuery();
while(rs.next()){
int ad = rs.getInteger("Score");
int fad = ad+reg;
String sql2 = "update db_table set Score=Score + "+fad+" where _ID=db_table.ID";
pst=con.prepareStatement(sql2);
pst.execute();
}
}catch(SQLException | HeadlessException e){
JOptionPane.showMessageDialog(null,e);
}finally{
try{
rs.close();
pst.close();
}
catch(Exception e){}
}

Why get null empty varchar record and 0 as date record when using Java insert value into mysql?

I tried insert a roll using Java from eclipse to MySQL. I got not error notification. However, when I select record from table, I got empty records in varchar type column and 0000-00-00 in date type column.
Here are code:
import java.sql.*;
public class Database {
public static void main(String[] args){
try{
String url = "jdbc:mysql://localhost/employees";
String user = "DDD";
String pwd = "123456";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(url, user, pwd);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from employees");
PreparedStatement ps = null;
AddEmployees newAddEmployees = new AddEmployees("555-55-5555", "DDD", "LLL", "1990-1-1", "programmerEmployee", "DEVELOP");
ps = conn.prepareStatement(newAddEmployees.Insert());
ps.executeUpdate();
while (rs.next()){
String socialSecurityNumber = rs.getString("socialSecurityNumber");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String birthday = rs.getString("birthday");
String employeeType = rs.getString("employeeType");
String departmentName = rs.getString("departmentName");
System.out.println(socialSecurityNumber + ", " + firstName + ", " + lastName + ", " + birthday + ", " + employeeType + ", " + departmentName);
}
rs.close();
conn.close();
}
catch(Exception ex){
System.out.println("Error: " + ex.toString());
}
}
}
Here are other code in the AddEmployees class:
public class AddEmployees extends Employees{
public AddEmployees(String socialSecurityNumber, String firstName, String lastName, String birthday,
String employeeType, String departmentName) {
this.socialSecurityNumber = socialSecurityNumber;
this.firstName = firstName;
this.lastName = lastName;
this.birthday = birthday;
this.employeeType = employeeType;
this.departmentName = departmentName;
}
#Override
public String Insert() {
return SQLStatement = "insert into employees(socialSecurityNumber, firstName, lastName, birthday, employeeType, departmentName)"
+ "values (+socialSecurityNumber, +firstName, +lastName, +birthday, +employeeType, +departmentName)";
}
}
Here is what I got in MySQL:
mysql> select * from employees;
+----------------------+-----------+----------+------------+----------------------------+----------------+
| socialSecurityNumber | firstName | lastName | birthday | employeeType | departmentName |
+----------------------+-----------+----------+------------+----------------------------+----------------+
| | | | 0000-00-00 | | |
| 111-11-1111 | John | Smith | 1945-01-02 | salariedEmployee | R&D |
| 222-22-2222 | Sue | Jones | 1961-02-03 | commissionEmployee | SALES |
| 333-33-3333 | Bob | Lowis | 1958-10-05 | basePlusCommissionEmployee | SALES |
| 444-44-4444 | Karen | Price | 1972-05-25 | hourlyEmployee | HR |
+----------------------+-----------+----------+------------+-------------------
---------+----------------+
5 rows in set (0.02 sec)
Your Insert() method returns the literal string
insert into employees(socialSecurityNumber, firstName, lastName, birthday, employeeType, departmentName)
values (+socialSecurityNumber, +firstName, +lastName, +birthday, +employeeType, +departmentName)
You probably ment to insert your parameters instead of +socialSecurityNumber, +firstName, ... - but what you return is just a static String. Because your values are valid column names of your table, you don't get an error, and what will be inserted are the default values for the columns.
You shouln't try to use string replacement to create an SQL query anyway, that only leads to sql injection vulnerabilities in your code.
This is how PreparedStatements are intended to be used:
PreparedStatement ps = conn.prepareStatement("insert into employees(socialSecurityNumber, firstName, lastName, birthday, employeeType, departmentName) "
+ "values (?, ?, ?, ?, ?, ?)");
ps.setInt(1, socialSecurityNumber);
ps.setString(2, firstName);
...
ps.executeUpdate();

MySQL create or alter table

I am using MySQL 5.1 for my database and I'm sending the commands via a Java program (JBDC).
Is there a MySQL command for creating or altering a table?
Let's say I have a following table:
+----------+----------+
| column_a | column_b |
+----------+----------+
| value_a | value_b |
+----------+----------+
Now I want to use a command, that would add a column "column_c" if it didn't exist.
That would result in:
+----------+----------+----------+
| column_a | column_b | column_c |
+----------+----------+----------+
| value_a | value_b | |
+----------+----------+----------+
If the table didn't exist, it would create a new table with specified columns:
+----------+----------+----------+
| column_a | column_b | column_c |
+----------+----------+----------+
And finally, if the table had columns that weren't specified in the command, it would leave them untouched.
here is code in Java to create a table called Coffees:
/*Making the connection*/
try {//if any statements within the try block cause problems, rather than the program failing
//an exception is thrown which will be caught in the catch block
con = DriverManager.getConnection(url, "your username", "your password");
//create a statement object
stmt = con.createStatement();
//supply the statement object with a string to execute
stmt.executeUpdate("create table COFFEES (COF_NAME varchar(32), " +
"SUP_ID int, PRICE double, SALES int, TOTAL int, " +
"primary key(COF_NAME))");
//close the statement and connection
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
Explanation:
-In this example the java program interacts with a database that is located on a server, so we have to firstly we set the url of where the server is located and also sign in username and password, you may not be using the same method that I used.
-These need to be declared at the top of your java program:
String url = "jdbc:mysql://www.yoururlexample.co.uk";
Connection con;
Statement stmt
Hopefully this helps, you will then be able to insert data into the database and execute queries.
Edit:
This can be used in the executeUpdate statement if you want a table to be created if none exists with the name "COFFEES":
create table if not exists COFFEES
/*Making the connection*/
try {
//an exception is thrown which will be caught in the catch block
con = DriverManager.getConnection("jdbc:mysql:exaple.com", "username", "pass");
//create a statement object
stmt = con.createStatement();
//supply the statement object with a string to execute
stmt.executeUpdate("ALTER TABLE table_name ADD column_name datatype");
//close the statement and connection
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
I think that this is going to work for you.
Something like that might be a solution (this need at least one record in the table to work):
package com.stackoverflow.so20935793;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class App {
// complete this:
private static final String JDBC_URL = ".....";
private static final String JDBC_USER = ".....";
private static final String JDBC_PASS = ".....";
public static void main(final String[] args) {
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASS);
stm = con.prepareStatement("SELECT * FROM your_table LIMIT 1");
rs = stm.executeQuery();
if (rs.next() && rs.getMetaData().getColumnCount() == 2) {
// add your new column
}
} catch (final SQLException ex) {
// handle exception
} finally {
closeQuietly(rs);
closeQuietly(stm);
closeQuietly(con);
}
}
private static void closeQuietly(final AutoCloseable what) {
if (what == null) {
return;
}
try {
what.close();
} catch (final Exception ex) {
// ignore
}
}
}
(not tested)

Categories

Resources