Multiple keyword search with Java & MySQL - java

I'm trying to write a Java code snippet to return the keywords contained in the description of a specific entity & SELECT only those records that contain both keywords.
The following code works, however it returns entities whose body contains only one or the other of the words. I need it to return only those records that contain both keywords, not just one of them.
try {
String search = txt_search.getText();
search = search.trim();
search = search.replace (' ','|');
String sql = "SELECT * FROM catagory WHERE keywords REGEXP '" + search + "'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()){
String add1 = rs.getString("CatagoryId");
txt_catagoryid.setText(add1);
String add2 = rs.getString("CatagoryName");
txt_catagoryName.setText(add2);
String add3 = rs.getString("keywords");
txt_keywords.setText(add3);
rs = stmt.executeQuery(sql);
catagoryTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception e){
...
}

Related

Why does alphanumeric id search not working properly in Java Swing?

I have a search field in Java swing to search Books. I have UI having text field jtxtSearch to enter values and one Field JCombobox for categories. Though it's working for all other fields but not for id search. However when having a pretext in the book id (eg: sp001) its working and populating on jtable. My code is as below.
public List<Book> searchBookBy(String search, String field){
List<Book> results = new ArrayList<Book>();
String sql = null;
Statement stmt = null;
ResultSet rs = null;
if(field.equalsIgnoreCase("id")){
if(search.length() == 0) search = "0";
sql = "SELECT * FROM books WHERE id = " + search;
}else{
sql = "SELECT * FROM books WHERE " + field + " LIKE '%" + search + "%'";
}
After this is my try and catch to set variable id etc. The DB is MySQL.

find a name in a sqlite table and return the id?

What I'm trying to do seems simple but I get this error SQLITE_ERROR] SQL error or missing database (no such column: user1)
public String getIdUser(String name) {
try {
this.stat = conn.createStatement();
String sql = "SELECT id_user FROM User WHERE name = " + name;
ResultSet user = stat.executeQuery(sql);
return user.toString();
} catch (SQLException e) {
return null;
}
}
Replace
String sql = "SELECT FROM User WHERE name = " + name;
with
String sql = "SELECT * FROM User WHERE name = " + name; // you can also specify a column/columns instead of *
I see many problems in your code :
First
Your query should return something it should be :
SELECT col_name1, col_name2, ... FROM User ...
Or if you want to select every thing :
SELECT * FROM User ...
Second
String or Varchar should be between two quotes, your query for example should look like :
SELECT col_name1 FROM User WHERE name = 'name'
Third
I don't advice to use concatenation of query instead use Prepared Statement it is more secure and more helpful (I will provide an example)
Forth
To get a result you have to move the cursor you have to call result.next()
Fifth
Name of variable should be significant for example ResultSet should be ResultSet rs not ResultSet user
Your final code can be :
PrepareStatement prst = conn.prepareStatement("SELECT colName FROM User WHERE name = ?");
prst.setString(1, name);
ResultSet rs = prst.executeQuery();
if(rs.next()){
reuturn rs.getString("colName");
}
Without quoting the name string it's interpreted as column name, and thus the error you see. You could surround it with single quotes, but that's still generally a bad practice, and will leave the code vulnerable to SQL injection attacks.
Additionally, you're missing the select list (specifically, the id_user column), and missing getting it from the result set.
And finally, you forgot to close the statement and the result set.
If you put all of these corrections together, you should use something like this:
public String getIdUser(String name) {
try (PreparedStatmet ps =
conn.prepareStatement("SELECT id_user FROM User WHERE name = ?")) {
ps.setString(1, name);
try (ResultSet rs = stat.executeQuery()) {
if (rs.next()) {
return rs.getString(1);
}
}
} catch (SQLException ignore) {
}
return null;
}

Can't print information from SQL in Java

The user must choose a Resort ID from the table that is displayed and the make a booking. I can't seem to find my problem, I want to print the name of the Resort that they are making a booking at.
String x = jTextFieldID.getText();
Integer Resort = Integer.valueOf(x);
int resort = Integer.parseInt(x);
String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = "+Resort;
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, resort);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
String resortName = rs.getString("RESORT_NAME");
JOptionPane.showMessageDialog(null,
"You want to book at " + resortName);
}
You have to use rs.next() :
ResultSet rs = pstmt.executeQuery(sql);
String resortName = "";
if(rs.next()){//<<-----------------------------
resortName = rs.getString("RESORT_NAME");
}
JOptionPane.showMessageDialog(null, "You want to book at "+resortName);
If you want to get many results you can use while(rs.next){...} instead.
Note? for a good practice, don't use upper letter in beginning for the name of your variables ResortName use this instead resortName
You need to test over the ResultSet result before trying to read from it:
if(rs.next()) {
String ResortName = rs.getString(1);
JOptionPane.showMessageDialog(null, "You want to book at "+ResortName);
}
And you can use getString(1) to get the RESORT_NAME, check ResultSet .getString(int index) method for further details.
The error is that sql is passed to Statement.executeQuery(String) too, instead of the PreparedStatement.executeQuery().
int resort = Integer.parseInt(x);
//String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = ?";
String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = " + resort;
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
//pstmt.setInt(1, resort);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
String resortName = rs.getString("RESORT_NAME");
JOptionPane.showMessageDialog(null,
"You want to book at " + resortName);
}
}
} catch (SQLException ex) {
Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex);
}
Commented is the alternative usage of a prepared statement (as normally used).
Also you should close statement and result set, which can be done automatically with try-with-resources as above.
Oh, oversaw almost, that rs.next() must be called. (The others already mentioned.)

Populating other jcombox that refers to the first jcombobox

Hi I am new here and I need some help in populating other jcomboboxes. All I wanted is that if I will select Last name from the first combobox, the other combobox will be populated by First names of patients/persons that has same Lastnames same as the Middlename. I hope you can help me
here's the pic:sample
As of now this is the code that I got to get values from database and put it on the first jcombobox:
public void lastname(){
try{
Connection con = (Connection)DriverManager.getConnection("jdbc:mysql://localhost/javaclinic", "root","");
String sql1 = "select * from patient";
PreparedStatement pst1 = con.prepareStatement(sql1);
ResultSet rs1 = pst1.executeQuery();
while(rs1.next()){
lastn.addItem(rs1.getString("PLastname"));
}
}
catch(SQLException e){
}
}
Modify the sql to search database , if user enter any value like:
String sql1 = "SELECT * FROM patient";
if(lastName.equals(""))
{
sql1 +=" WHERE PLastName = '" + lastName + "'";
}

Fill jTextField with records when selecting from jComboBox (Java database)

How do you go about putting records into a jTextField when an item is selected from a jComboBox? For example, I'm making an airline reservation system and I have a combo box with the available flights. Below it are text fields with designated info like departure date, departure time, arrival date, etc. How do I make it so that when the user selects an item from the the combo box, (ex. flight name is CX9005) the corresponding info from the same row is shown in the text fields? (ex. departure date is November 12 2015)
EDIT:
So I tried doing that with the ff. code, but I got a syntax error and a ResultSet not open error.
private void combo_FlightItemStateChanged(java.awt.event.ItemEvent evt) {
try{
flightID = combo_Flight.getSelectedItem().toString();
String flightName = combo_Flight.getSelectedItem().toString();
String query = "Select * from ACCOUNTS where flightName = \'"+flightName+"\';";
rs = stmt.executeQuery(query);
}
catch(SQLException err){
JOptionPane.showMessageDialog(UserModule.this, err.getMessage());
}
}
Also, I use this function to connect to my database if that matters.
public void DoConnect() {
try{
String host = "jdbc:derby://localhost:1527/UserAccounts";
String uName = "Bryan";
String uPass = "Cruz";
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM ACCOUNTS";
rs = stmt.executeQuery(sql);
}catch(SQLException err){
JOptionPane.showMessageDialog(Connect.this, err.getMessage());
}
}
Also, I might not have been too clear with my original post. I want to make it so that when the user selects a flight from the combo box, all of that flight's details show up in the appropriate text fields. (ex. departure date, departure time, destination, etc.) I'm confused on how to make this work so help would be much appreciated!
You get the text from the comboBox using getSelectedItem() or getSelectedValue().
You can then create a MySQL query like:
String flightName = yourComboBox.getSelectedItem().toString();
String query= "Select * from yourTable where flightName = \'"+flightName+"\';";
Then you can execute this query using executeQuery()
Now for the part with setting results in all testfields
First store the result in a ResultSet object
rs = stmt.executeQuery(query);
rs.next();
Now you have the result in object rs
Use rs.getString(columnNumber) to get records from the result
Eg.
String departureDate = rs.getString(4);
// assuming the column number is 4
Do this to get all required strings.
And set them in respected columns using setText() method
flightID = combo_Flight.getSelectedItem().toString();
String flightName = combo_Flight.getSelectedItem().toString();
What is the point of the above two statements? You can't get two values from the same combo box. Either you get the flightID or the flighName.
String query = "Select * from ACCOUNTS where flightName = \'"+flightName+"\';";
but I got a syntax error
Don't try to build the SQL string manually. Instead you can use a PreparedStatement. It will make sure the proper delimiters are used so you just concentrate on the SQL statement:
String flightName = combo_Flight.getSelectedItem().toString();
String query = "Select * from ACCOUNTS where flightName = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString( 1, flightName );
ResultSet rs = stmt.executeQuery();
So you will need access to the Connection object you established in the doConnect() method. Note, method names should NOT start with an upper case character.
Also, I believe the standard for database column names is to capitalize the words of the column, so you should be using "FlightName" not "flightName" as the column name.

Categories

Resources