Searching the Mysql database with Autocomplete on JTable using textfield - java

Could you please tell me what to add on my code so that when i type a letter in the textfield, before i finish typing the search result already start showing on jtable without waiting for me to type the whole word?
Below please find my code for key released event on the textbox. Thank you for your help.
private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {
try{
String selected=(String)jComboBoxSelected.getSelectedItem();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
+ "employee_certificate","root","");
String sql="SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n" +
"certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+ "WHERE "+selected+" =? ORDER BY stuff.Emp_Name\n" ;
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, jTextFieldSearch.getText());
ResultSet rs=pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
pstmt.close();
//con.close();
}
catch(Exception ex){ex.printStackTrace();}
}

After a two day struggle finally i got an answer...i just needed to use LIKE '%' as shown.No one should suffer as i did
private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {
try{
String selected=(String)jComboBoxSelected.getSelectedItem();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+ "employee_certificate","root","");
String sql="SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n" +
"certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+"WHERE "+selected+" LIKE ? ORDER BY stuff.Emp_Name\n" ;
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1,jTextFieldSearch.getText() + "%");
ResultSet rs=pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
pstmt.close();
con.close();
}
catch(Exception ex){ex.printStackTrace();}
}

Related

JavaFX update a Sqlite table

I am currently working on a program the function of which is to store my passwords, and this is why I am using an SQL database called Users. This database contains tables for all the users which will be using the program. Those tables have four columns:
SiteName, Username, Password, AdditionalInfo
I am having a problem updating a specific row. This is my the code I get an error with:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
c.setAutoCommit(false);
stmt = c.createStatement();
String update = "UPDATE " + user + " set Username = " + usernamej + " where SiteName = " + siteEdited;
stmt.executeUpdate(update);
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
It is in a class made specifically for dealing with the sql database and it gets the following error when I try to change the username to 'test':
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such column: test)
Assuming the value you pass in for user is the name of the table, your update string is going to look like
UPDATE usertable SET Username = test where SiteName = siteEditedValue
You need to quote the string values:
UPDATE usertable SET Username = 'test' where SiteName = 'siteEditedValue'
The quick and dirty way is:
String update = "UPDATE " + user + " set Username = '" + usernamej + "' where SiteName = '" + siteEdited + "'";
However, it's much (much, much) better to use a PreparedStatement in this case:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
stmt = c.prepareStatement("UPDATE " + user + " SET Username = ? Where SiteName = ?");
stmt.setString(1, usernamej);
stmt.setString(2, siteEdited);
stmt.executeUpdate();
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
This code assumes the type of stmt is PreparedStatement, not just Statement.
As well as taking care of quoting the values for you, this will escape any sql for you, preventing the possibility of SQL-injection attacks (while these are far less of an issue in a desktop application that a web application, it's still a good habit to get into).
#griFlo I got it running with this code:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
c.setAutoCommit(false);
PreparedStatement stmt = c.prepareStatement("UPDATE " + user + " SET Username = ? Where SiteName = ?");
stmt.setString(1, usernamej);
stmt.setString(2, siteEdited);
stmt.executeUpdate(update);
c.commit();
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
I had forgotten to put c.commit();

Connecting to database with Java

In preparation for an exam I am asked to debug and answer the questions below, but this goes over my head. Help much appreciated.
Assuming the syntax is correct, why will this code produce an
error when connecting to the database?
Suggest two ways how to improve security of database connection in this code.
import java.sql.*;
public class UpdateCar {
public static void updateCarNum (int carNo, int empNo)
throws SQLException {
Connection con=null;
PreparedStatement pstmt=null;
try {
con = DriverManager.getConnection(
"jdbc:default:connection");
pstmt= con.prepareStatement("UPDATE EMPLOYEES " +
"SET CAR_NUMBER = ? " +
"WHERE EMPLOYEE_NUMBER = " + empNo);
pstmt.setInt(2, empNo);
pstmt.executeUpdate();
}
finally {
if (pstmt != null) pstmt.close();
}
}
}
Change
pstmt= con.prepareStatement("UPDATE EMPLOYEES " +
"SET CAR_NUMBER = ? " +
"WHERE EMPLOYEE_NUMBER = " + empNo);
pstmt.setInt(2, empNo);
to
pstmt= con.prepareStatement("UPDATE EMPLOYEES " +
"SET CAR_NUMBER = ? " +
"WHERE EMPLOYEE_NUMBER = ?");
pstmt.setInt(1, carNo);
pstmt.setInt(2, empNo);
And you should also read a bit about what JDBC is, and how to use it.
Check your DiverManager. in java there is jdbc driver that may not work with your database . try another driver for your connection

Adding database column to JComboBox

I've searched around for the answer to this, but to no avail. When I compile this, it just returns the last row of my table in the database and not a list of the entire column as I expect. I believe the problem is from here.. If only I can make it list everything in that column, I'd be grateful for your help.
String query = "SELECT contact_id, first_name, last_name FROM my_contacts";
ResultSet rs = statement.executeQuery(query);
while (rs.next())
{
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
String name = rs.getString(2) + " " + rs.getString(3);
names = new JComboBox();
names.addItem(rs.getString("first_name"));
}//end while
When I compile this, it just returns the last row of my table in the
database and not a list of the entire column as I expect. I believe
the problem is from here..
while (rs.next())
{
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
String name = rs.getString(2) + " " + rs.getString(3);
names = new JComboBox();
names.addItem(rs.getString("first_name"));
}
your code created a new instance of JComboBox, in each of loop inside while (rs.next()){
create JComboBox as local variable, then just to add Items in while-loop to instance that already exist and is intialized
best of ways is by using DeafultComboBoxModel for add / remove / modify an Items for JComboBox
Got everything up and running with this code.
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/recall", "username", "password");
Statement statement = connection.createStatement();
String query = "SELECT * FROM names";
ResultSet rs = statement.executeQuery(query);
while (rs.next())
{
String name = rs.getString("name");
names.addItem(rs.getString("name"));
}//end while
connection.close();
} catch (Exception e) {
e.printStackTrace();
}

SQLException - invalid cursor state

I am coding a simple CRUD Application in java and I have a Method to select Produkts that go with bills.
Here is my code:
public Rechnung selectProdukte(int target){
int tempProdukt;
int tempAnzahl;
try {
PreparedStatement ps1=hsqlmanager.getConnection().prepareStatement("SELECT produkt, anzahl from gekauftes_produkt " +
"WHERE rechnung= " + target + ";");
//ps1.setInt(1, target);
//Query 1wird executiert
PreparedStatement ps2 = hsqlmanager.getConnection().prepareStatement("SELECT * FROM rechnung WHERE id= " + target + ";");
//ps2.setInt(1, target);
ResultSet rs1 = ps1.executeQuery();
ResultSet rs2 = ps2.executeQuery();
Rechnung erg=new Rechnung();
erg.setId(rs2.getInt(1));
erg.setDatum(rs2.getDate(2));
erg.setSumme(rs2.getDouble(3));
while(rs1.next()){
tempProdukt=rs1.getInt(1);
tempAnzahl=rs1.getInt(2);
erg.addGekauftTupel(tempProdukt, tempAnzahl);
}
ps1.close();
ps2.close();
return erg;
} catch(Exception e) {
log.error("Fehler in DAO Rechnung - selectProdukte: " + e);
}
return null;
}
When I press the Button to execute the code I get:
java.sql.SQLException: invalid cursor state: identifier cursor not
positioned on row in UPDATE, DELETE, SET, or GET statement: ;
ResultSet is positioned before first row
I checked the db and all the tables and entities exist. So my question is:
What does that mean?
I appreciate your answer!!!
PS.: I am using hsql db!
you have not called rs2.next() before accessing erg.setId(rs2.getInt(1));

what's wrong with my insert statement? mysql java

what's wrong with my insert method?
my table has two columns, name, and artist..and timestamp, that too
actually, how do i pass timestamp argument to the insert statement?
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
/*FileWriter dir = new FileWriter(nameOfSong.getText()
+ ".txt");
BufferedWriter buffer = new BufferedWriter(dir);
buffer.write(nameOfSong.getText());
buffer.newLine();
buffer.write(artist.getText());
buffer.newLine();
buffer.newLine();
buffer.write(lyrics.getText());
buffer.close();
*/
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES(" +
nameOfSong.getText() + ", " + artist.getText() + "");
} catch (Exception z) {
System.err.println("Error: " + z.getMessage());
}
internalFrame.dispose();
}
});
)
Always use PreparedStatement.
String sql="INSERT INTO lyrics1_lyrics1 VALUES (?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,nameOfSong.getText());
statement.setString(2,artist.getText());
statement.executeUpdate();
statement.close();
connection.close();
The text values need to be surrounded by single quotes ('').
And SQL-escaped to avoid SQL injection attacks, or the first time you have a song by Little Bobby Tables, all your DB are belong to him.
Better yet, use a PreparedStatement, and let the machine do work for you.
You can use prepared statement for it
String query = "INSERT INTO lyrics1_lyrics1(name, artist, timestamp) values(?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, name); // set input parameter 2
pstmt.setString(2, artist);
pstmt.setString(3, new TimeStamp(new Date().getTime()));
You need to add an import statement for the TimeStap;
import java.sql.Timestamp;
or else use
pstmt.setString(3, new java.sql.TimeStamp(new Date().getTime()));
Example: Prepared Statement Insert.
You can find a lot of example in java2s site.
Change the line to:
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES('" +
nameOfSong.getText() + "', '" + artist.getText() + "'");
This might solve your problem:
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES('" + nameOfSong.getText() + "', '" + artist.getText() + "')");`

Categories

Resources