I am developing simple swing application to get some information from the database.
Two of the field in database table called Used_PR & Create_PR.
As follows,
Data structure is like mention below.
PR-L-Machine-Date-Shift
Then I want to retrieve data by PR.
Here is my interface to insert search details
Date choose from date JDateChooser.
I used LIKE clause to get data from the db, but it does not work.
Here is the MYSQL query statement.
String prlQuery = "SELECT * FROM final_report WHERE used_PR LIKE '?%' OR create_PR LIKE '?%'";
try {
Date chooseDate = new Date(dateChooser.getDate().getTime());
String parameter = "PR-L-" + selectMachine.getSelectedItem() + "-" + chooseDate;
pst = connect.dbConnection().prepareStatement(prlQuery);
pst.setString(1, parameter);
pst.setString(2, parameter);
But seems it is not working. Can somebody help me with this code structure.
You must pass the % in the parameters
your query must look like
String prlQuery = "SELECT * FROM final_report WHERE used_PR LIKE ? OR create_PR LIKE ?";
try {
Date chooseDate = new Date(dateChooser.getDate().getTime());
String parameter = "PR-L-" + selectMachine.getSelectedItem() + "-" + chooseDate;
pst = connect.dbConnection().prepareStatement(prlQuery);
pst.setString(1, parameter+"%");
pst.setString(2, parameter+"%");
Related
The query inside MySQL is working:
DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'
I can delete data inside MySQL, but the problem is whenever I try to remove the account_tags from my Java application, it throws an error:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'' at line 2
Here's my Java SQL query:
Statement statement = dbConnection.createStatement();
String sql = "SELECT * FROM "+databaseName+"."+tableName+";\n" +
"DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = '"+AccountTag+"';";
statement.executeQuery(sql);
The error isn't giving me much to work with, so I really have no idea what is wrong with the program.
Did you add the allowMultiQueries=true
If not then you can add that while you sending the connecting request to your database. So you need to append the allowMultiQueries=true in your to database URL.
Like this:
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
String sql = "DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
int updateCount = statement.executeUpdate();
System.out.printf("%s: %d records deleted.%n", tableName, updateCount);
}
The only thing used is the DELETE, for which one should use executeUpdate.
One definitely should use a PreparedStatement as many code checkers will give alarms otherwise. It escapes things like ', handles types of the arguments, and possible conversions, and especially is a security feature against SQL injection.
The System.out usage is bad style, better would be using a logger.
try-with-resources automatically closes the PreparedStatement even with a raised exception or break/return.
When doing both database operations, it seems better to use two (prepared) statements, as the first returns a ResultSet.
So:
String sql = SELECT * FROM "+databaseName+"."+tableName + "\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
try (ResultSet rs = statement.executeQuery()) {
...
}
}
Better to separate statements with an If condition :
String sql1="SELECT * FROM "+databaseName+"."+tableName;
String sql2="DELETE FROM "+databaseName+"."+tableName+" "+
"WHERE account_tags = '"+AccountTag+"';
statement.executeQuery(sql1);
statement.executeUpdate(sql2);
I'm having problem with showing database values in my Jtable. I don't know how to use JDataChooser as a searching tool in JTable. I want the process like this, if JDateChooser1 is select to 08-17-2017 and JDateChooser2 is select 09-17-2017
the JTable will only show the values that having that date between 08-17-2017 - 09-17-2017. The format of the Date is (MM-dd-yyyy).
I have this method and as a testing I put the method to a button. I also want to know where I can put this method to be able not using a button. Auto search when I'm done selecting the dates.
sales is my table name in mysql and Date is the column name.
private void Dated() {
try {
String value1, value2;
value1 = jDateChooser1.getDate().toString();
value2 = jDateChooser2.getDate().toString();
String sql = "select * from sales where Date = '" + value1 + "' and '" + value2 + "'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
You are missing some information in your query :
show the values that having that date between 08-17-2017 - 09-17-2017 you have to use between keyword in the query should be select * from sales where Date between date1 and date1 and not =
because you are using prepapred statement don't use concatination of the query and values.
beside Date is reserved keyword in MySQL instead you have to put it between two ``
Your code should look like :
Date value1 = jDateChooser1.getDate();
Date value2 = jDateChooser2.getDate();
String sql = "select * from sales where `Date` between ? and ?";
pst = conn.prepareStatement(sql);
pst.setDate(1, value1);
pst.setDate(2, value2);
rs = pst.executeQuery();
I'm trying to get some data from Oracle 11.2 using java and jdbc driver.
My goal is to get data from database using CallableStatement, but with no luck - I'm not able to put table name as parameter. I would like to have configurable table name in query. However, it would be good to keep it sanitized.
Here is an example..
public void getData() throws SQLException {
Connection conn = Config.getSQLConnection();
String query = "SELECT * FROM ?";
PreparedStatement st = conn.prepareStatement(query);
st.setString(1, Config.DATATABLE_NAME);
ResultSet rs = st.executeQuery();
if (rs.next()) {
System.out.println("SUCCESS");
System.out.println("ID:" + rs.getString("ID"));
} else {
System.out.println("FAILURE");
}
}
Is this the way it should work? Or am I missing something, or misused it?
A CallableStatement is used to make call to stored procedures.
From javadoc:
The interface used to execute SQL stored procedures
Use a PreparedStament instead for a normal select.
As an additional note don't pass the name of the table as parameter.
Create the query using concatenation.
Instead of
String query = "SELECT * FROM ?";
use
String query = "SELECT * FROM " + Config.DATATABLE_NAME;
You should use PreparedStatement instead of CallableStatement.
CallableStatement is an interface which is used to call stored procedures.
I am writing a program, where the user will be receiving instructions in different languages. I have the tables structures by language, so based on the user's language user settings, the corresponding language table will be selected. However, I keep getting errors from the following code.
String query2 = "select * from ? where instruction_id = ?";
PreparedStatement pst2 = connection.prepareStatement(query);
pst2.setString(1, user_config.language);
pst2.setString(2, instruction_id);
ResultSet rs2 = pst2.executeQuery();
Can someone explain why the above code is not working?
I ended up using string concatenation for the table name.
String query2 = "select * from " + user_config.language + " where instruction_id = ?";
PreparedStatement pst2 = connection.prepareStatement(query2);
When I view the database and run this query I get results as expected.
SELECT * FROM users WHERE options LIKE '%[-15,-3]%';
However when I use a prepared statement as seen below, the uuid is null.
String opt = "[-15,-3]"; //example
PreparedStatement ps = SQLite.connection.prepareStatement(
"SELECT * FROM users WHERE options LIKE '%" + opt + "%'"
);
ResultSet rs = ps.executeQuery();
String uuid = null;
while (rs.next()){
uuid = rs.getString("member");
}
rs.close();
ps.close();
if(uuid != null){
System.out.println("not null: " + uuid);
return Database.getUser(UUID.fromString(uuid);
}
For the code above, nothing is returned in the result set. Which is very strange because I used the same query with an SQLite viewer and it returned the proper rows. How can I solve this? I don't see an issue.
UPDATE
When I directly use "SELECT * FROM factions WHERE claims LIKE '%[-15,-3]%'" in the prepared statement instead of the variable, it works fine. Why can't I use a string variable? I've checked the variable and it prints to console fine.
I solved it after a lot of trial and error, turns out I should've been using a ? and set the string.
PreparedStatement ps = SQLite.connection.prepareStatement(
"SELECT * FROM users WHERE options LIKE ?"
);
ps.setString(1, "%" + opt + "%");