SQL WHERE LIKE clause in JSF managed bean - mysql

Hi i have this managed bean where it makes MySQL queries, the problem here is the SQL statement makes a '=' condition instead of 'LIKE'
Here is the code in my managed bean.
Connection con = ds.getConnection();
try{
if (con == null) {
throw new SQLException("Can't get database connection");
}
}
finally {
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM Clients WHERE Machine LIKE '53'");
//get customer data from database
ResultSet result = ps.executeQuery();
con.close();
List list;
list = new ArrayList();
while (result.next()) {
Customer cust = new Customer();
cust.setMachine(result.getLong("Machine"));
cust.setCompany(result.getString("Company"));
cust.setContact(result.getString("Contact"));
cust.setPhone(result.getLong("Phone"));
cust.setEmail(result.getString("Email"));
//store all data into a List
list.add(cust);
}
return list;
Here the SELECT command does not pull all the numbers in 'Machine' column which is like 53, but if i enter a whole value, such as the complete number (53544) in place of 53 then the result is pulled up. I am confused !!
Also if i replace the above select statement with SELECT * FROM Clients the entire database is stored in list. Any ideas ?

Use wildcards:
Like '%53%'
...means everything that contains '53'.
Like '%53' - it ends with 53
LIKE '53%' - it starts with 53
You can also use _ if You want to replace a single character.
You can find a descriptipn HERE

You sql query should be
"SELECT * FROM Clients WHERE Machine LIKE '%53%'

Related

How I can get the correct date of my Mysql query without the query itself subtracting one day to date

My problem is that in a table of my database with 7 columns, I have a column of date type, called "Fecnac". Through MYSQLworkbrench, I execute a simple query:
"SELECT * FROM tblAsegurados ORDER BY Name,Nss"
As a result of this query, the information of my columns or fields of the table is displayed, the table contains a column named "Fecnac" that shows the correct date, for example "2018-12-31".
MYSQLworkbrench Result image
However, I developed an application in intelliJ IDEA to execute the same query, and the query "by itself" returns the date with one day less, that is, it shows "2018-12-30". And so it does with all the dates found in the "Fecnac" column of the "tblAsegurados" table in my database.
public ArrayList<Asegurados> getAseguradosList(){
ArrayList<Asegurados> aseguradosList = new ArrayList<Asegurados>();
Connection connection = getConnection();
var query = "select * from tblAsegurados order by Nombre,Nss";
Statement st;
ResultSet rs;
try{
st = connection.createStatement();
rs = st.executeQuery(query);
Asegurados asegurado;
while(rs.next()){
asegurado = new Asegurados(
rs.getString("Nss"),
rs.getString("Nombre"),
rs.getString("Curp"),
rs.getBoolean("Esposa"),
rs.getInt("Semcot"),
rs.getInt("Hijos"),
rs.getDate("Fecnac"));
aseguradosList.add(asegurado);
System.out.println(asegurado.getFecnac());
System.out.println(rs.getDate("Fecnac"));
System.out.println(rs.getDate(7));
}
} catch (Exception e){
e.printStackTrace();
}
return aseguradosList;
}
The class "Asegurados" has an attribute of type "java.sql.date" defined, to receive "rs.getdate (Fecnac).
For i be sure of the values ​​returned by the query, in my code you can see that I made a "System.out.println" for each field date, and in all three I get the same value from the date with one day less.
Could someone help me know what happens?
Console debug IntelliJ Idea image
I already found the solution. In a part of my code, the parameter of the time zone had it defined as: serverTimezone = UTC
public static Connection getMySQLConnection() throws Exception {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost/imss"+
"?useUnicode=true&useJDBCCompliantTimezoneShift=true"+
"&useLegacyDatetimeCode=false&serverTimezone=America/Mexico_City"+
"&verifyServerCertificate=false"+
"&useSSL=true"+
"&requireSSL=true";
String username = "root";
String password = "juan1980";
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
I set it to: serverTimezone = america / Mexico_City, which is the zone that corresponds to me, and ready! the date is displayed correctly.

How to get output from NodeRed Mysql node

I want to get out put from NodeRed mysql node.
Here image of connection :
Select Query is :
msg.topic = "SELECT * t.TableID FROM booking t where t.bookingdate='"+formattedDate+"' and t.TableID = 3";
Output i am trying to get:
if(msg.payload.TableID ==3){
var id = "15";
var message = "Front Desk";
msg.topic = "INSERT INTO tableMessage(TableID, MESSAGE) VALUES ('"+id+"' ,'"+message+"')";
return msg;
}
Question is msg.payload.TableID ==3 is it right? is it right way to read out put from Mysql node
Select query are tested working fine.
but this condition not working for me.
any one help me how to retrieve data from mysql node.
Thanks
The output from the mysql node is an array of rows so your test should be something like this:
if (msg.payload[0].TableID ==3) {
...
EDIT:
You can test if no results were returned by testing the content of msg.payload
if (!msg.payload) {
//no results
} else if (msg.payload[0].TableID == 3) {
//results
}

jdbc mysql batch prepared call keeps only the last result set

I have a stored procedure call
call get(id);
in my database that would return a single row in a ResultSet object (it is basically a very long SELECT statement inside). Now in Java, I have a
int[] ids = {1,2,3}
and for each id in the list I want to call the stored procedure to get the record. So eventually I want a list of records corresponding to each id in ids. I attempted
Connection conn = ...;
PreparedStatement ps = conn.prepareCall("call get(?)");
for(int id : ids) {
ps.setInt(1, id); ps.addBatch();
}
ps.executeBatch();
with only the result of call
get(3);
is kept.
I also tried to move the SELECT statement directly as a String in Java, so it looks like
String stmt = "SELECT ... WHERE id=?"
PreparedStatement ps = conn.prepareStatement(stmt);
... // the for loop same as above
ps.executeBatch();
with a "Can not issue executeUpdate() for SELECTs". I tried
ps.executeQuery();
as the last line, but it also only has the result of the last SELECT.
I want to avoid a for loop that executes a SELECT a time because transferring data from the database to my computer has a very heavy overhead.
Can anyone help? Thank you in advance!
EDIT: I read Running the same select query multiple times with different parameters: Mysql , but in my case it is a little bit different, because in my select statement the id actually needs to be referenced several times; the code looks like this
SELECT * FROM
(SELECT ... FROM ... WHERE id=? AND ...),
(SELECT ... FROM ... WHERE id=? AND ...);
so it seems impractical to use the IN method. Also I have another call
call get2(aid, userId)
and a list of {{1, 1000}, {2, 2000}} which also does not fit this issue. Can anyone help? Thank you!

Deleting duplicate data in MySQL

I'm trying to emulate the accepted answer in this SO question: Delete all Duplicate Rows except for One in MySQL? [duplicate] with a twist, I want the data (auto-incrementing ID's) of one table to determine which rows to delete in another table. SQLFiddle here showing data.
In the fiddle referenced above, the end result I'm looking for is the rows in eventdetails_new with Event_ID = 4 & 6 to be deleted (EVENTDETAILS_ID's 5 & 6, and 9 & 10), leaving rows 3 & 5 (EVENTDETAILS_ID's 3 & 4 and 7 & 8). I hope that made sense. Ideally the rows in events_new with those same Event_ID's would get deleted as well (which I haven't started working on yet, so no code samples).
This is the query I'm trying to make work, but I'm a bit over my head:
SELECT *
FROM eventdetails_new AS EDN1, eventdetails_new AS EDN2
INNER JOIN events_new AS E1 ON `E1`.`Event_ID` = `EDN1`.`Event_ID`
INNER JOIN events_new AS E2 ON `E2`.`Event_ID` = `EDN2`.`Event_ID`
WHERE `E1`.`Event_ID` > `E2`.`Event_ID`
AND `E1`.`DateTime` = `E2`.`DateTime`
AND events_new.EventType_ID = 6;
Here's the same SQLFiddle with the results of this query. Not good. I can see the Event_ID in the data, but the query cannot for some reason. Not sure how to proceed to fix this.
I know it's a SELECT query, but I couldn't figure out a way to have two aliased tables in the DELETE query (which I think I need?). I figured if I could get a selection, I could delete it with some C# code. However ideally it could all be done in a single query or set of statements without having to go outside of MySQL.
Here's my first cut at the query, but it's just as bad:
DELETE e1 FROM eventdetails_new e1
WHERE `events_new`.`Event_ID` > `events_new`.`Event_ID`
AND events_new.DateTime = events_new.DateTime AND events_new.EventType_ID = 6;
SQLFiddle won't let me run this query at all, so it's not much help. However, it give me the same error as the one above: Error Code: 1054. Unknown column 'events_new.Event_ID' in 'where clause'
I'm by no means married to either of these queries if there's a better way. The end result I'm looking for is deleting a bunch of duplicate data.
I have hundreds of thousands of these results, and I know that roughly 1/3 of them are duplicates that I need to get rid of before we go live with the database.
Here's what I eventually ended up doing. My co-worker & I came up with a query that would give us a list of Event_ID's that had duplicate data (we actually used Access 2010's query builder and MySQL-ified it). Bear in mind this is a complete solution where the original question didn't have as much detail as far as linked tables. If you've got questions about this, feel free to ask & I'll try to help:
SELECT `Events_new`.`Event_ID`
FROM Events_new
GROUP BY `Events_new`.`PCBID`, `Events_new`.`EventType_ID`, `Events_new`.`DateTime`, `Events_new`.`User`
HAVING (((COUNT(`Events_new`.`PCBID`)) > 1) AND ((COUNT(`Events_new`.`User`)) > 1) AND ((COUNT(`Events_new`.`DateTime`)) > 1))
From this I processed each Event_ID to remove the duplicates in an iterative manner. Basically I had to delete all the child rows starting from the last lowest table so that I didn't run afoul of foreign key restraints.
This chunk of code was written in LinqPAD as C# statements: (sbCommonFunctions is an inhouse DLL designed to make most (but not all as you'll see) database functions be handled the same way or easier)
sbCommonFunctions.Database testDB = new sbCommonFunctions.Database();
testDB.Connect("production", "database", "user", "password");
List<string> listEventIDs = new List<string>();
List<string> listEventDetailIDs = new List<string>();
List<string> listTestInformationIDs = new List<string>();
List<string> listTestStepIDs = new List<string>();
List<string> listMeasurementIDs = new List<string>();
string dtQuery = (String.Format(#"SELECT `Events_new`.`Event_ID`
FROM Events_new
GROUP BY `Events_new`.`PCBID`,
`Events_new`.`EventType_ID`,
`Events_new`.`DateTime`,
`Events_new`.`User`
HAVING (((COUNT(`Events_new`.`PCBID`)) > 1)
AND ((COUNT(`Events_new`.`User`)) > 1)
AND ((COUNT(`Events_new`.`DateTime`)) > 1))"));
int iterations = 0;
DataTable dtEventIDs = getDT(dtQuery, testDB);
while (dtEventIDs.Rows.Count > 0)
{
Console.WriteLine(dtEventIDs.Rows.Count);
Console.WriteLine(iterations);
iterations++;
foreach(DataRowView eventID in dtEventIDs.DefaultView)
{
listEventIDs.Add(eventID.Row[0].ToString());
DataTable dtEventDetails = testDB.QueryDatabase(String.Format(
"SELECT * FROM EventDetails_new WHERE Event_ID = {0}",
eventID.Row[0]));
foreach(DataRowView drvEventDetail in dtEventDetails.DefaultView)
{
listEventDetailIDs.Add(drvEventDetail.Row[0].ToString());
}
DataTable dtTestInformation = testDB.QueryDatabase(String.Format(
#"SELECT TestInformation_ID
FROM TestInformation_new
WHERE Event_ID = {0}",
eventID.Row[0]));
foreach(DataRowView drvTest in dtTestInformation.DefaultView)
{
listTestInformationIDs.Add(drvTest.Row[0].ToString());
DataTable dtTestSteps = testDB.QueryDatabase(String.Format(
#"SELECT TestSteps_ID
FROM TestSteps_new
WHERE TestInformation_TestInformation_ID = {0}",
drvTest.Row[0]));
foreach(DataRowView drvTestStep in dtTestSteps.DefaultView)
{
listTestStepIDs.Add(drvTestStep.Row[0].ToString());
DataTable dtMeasurements = testDB.QueryDatabase(String.Format(
#"SELECT Measurements_ID
FROM Measurements_new
WHERE TestSteps_TestSteps_ID = {0}",
drvTestStep.Row[0]));
foreach(DataRowView drvMeasurements in dtMeasurements.DefaultView)
{
listMeasurementIDs.Add(drvMeasurements.Row[0].ToString());
}
}
}
}
testDB.Disconnect();
string mysqlConnection =
"server=server;\ndatabase=database;\npassword=password;\nUser ID=user;";
MySqlConnection connection = new MySqlConnection(mysqlConnection);
connection.Open();
//start unwinding the duplicates from the lowest level upward
whackDuplicates(listMeasurementIDs, "measurements_new", "Measurements_ID", connection);
whackDuplicates(listTestStepIDs, "teststeps_new", "TestSteps_ID", connection);
whackDuplicates(listTestInformationIDs, "testinformation_new", "testInformation_ID", connection);
whackDuplicates(listEventDetailIDs, "eventdetails_new", "eventdetails_ID", connection);
whackDuplicates(listEventIDs, "events_new", "event_ID", connection);
connection.Close();
//update iterator from inside the clause in case there are more duplicates.
dtEventIDs = getDT(dtQuery, testDB); }
}//goofy curly brace to allow LinqPAD to deal with inline classes
public void whackDuplicates(List<string> listOfIDs,
string table,
string pkID,
MySqlConnection connection)
{
foreach(string ID in listOfIDs)
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = String.Format(
"DELETE FROM " + table + " WHERE " + pkID + " = {0}", ID);
command.ExecuteNonQuery();
}
}
public DataTable getDT(string query, sbCommonFunctions.Database db)
{
return db.QueryDatabase(query);
//}/*this is deliberate, LinqPAD has a weird way of dealing with inline
classes and the last one can't have a closing curly brace (and the
first one has to have an extra opening curly brace above it, go figure)
*/
Basically this is a giant while loop, and the clause iterator is updated from inside the clause until the number of Event_ID's drops to zero (it takes 5 iterations, some of the data has as many as six duplicates).

Update table on mysql after a bigdecimal is declared

I have the following work on my application, in which I am trying to update the value total on my mysql database table called "porcobrar2012". However, the only value that gets updated is the last one generated in the while loop. Why? all values are been printout on the screen with no problem, but those values are not getting updated in the database.
Here is the code:
BigDecimal total = new BigDecimal("0");
try
{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Connection connection=DriverManager.getConnection("jdbc:odbc:db1","","");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost/etoolsco_VecinetSM?user=etoolsco&password=g7Xm2heD41");
Statement statement=connection.createStatement();
String query;
query="SELECT * FROM porcobrar2012";
ResultSet resultSet=statement.executeQuery(query);
while(resultSet.next())
{
out.println(resultSet.getString(2)+"");out.println(resultSet.getBigDecimal(3)+"");out.println(resultSet.getBigDecimal(4)+"");out.println(resultSet.getBigDecimal(5)+"");out.println(resultSet.getBigDecimal(6)+"");out.println(resultSet.getBigDecimal(7)+"");out.println(resultSet.getBigDecimal(8)+"");out.println(resultSet.getBigDecimal(9)+"");out.println(resultSet.getBigDecimal(10)+"");out.println(resultSet.getBigDecimal(11)+"");out.println(resultSet.getBigDecimal(12)+"");out.println(resultSet.getBigDecimal(13)+"")out.println(resultSet.getBigDecimal(14)+"");out.println(resultSet.getBigDecimal(15)+"");
total = resultSet.getBigDecimal(3).add(resultSet.getBigDecimal(4)).add(resultSet.getBigDecimal(5)).add(resultSet.getBigDecimal(6)).add(resultSet.getBigDecimal(7)).add(resultSet.getBigDecimal(8)).add(resultSet.getBigDecimal(9)).add(resultSet.getBigDecimal(10)).add(resultSet.getBigDecimal(11)).add(resultSet.getBigDecimal(12)).add(resultSet.getBigDecimal(13)).add(resultSet.getBigDecimal(14)).add(resultSet.getBigDecimal(15));
String query1;
query1="UPDATE porcobrar2012 SET total=total";
PreparedStatement ps = connection.prepareStatement(query1);
ps.executeUpdate();
out.println(total);
}
connection.close();
statement.close();
}
catch (Exception e)
{
//e.printStackTrace();
out.println(e.toString());
}
It's because the update closes the existing result set. But I would ask why you aren't doing the addition in a single UPDATE statement without any prior query, at the database, no loops, no BigDecimals. Rule one of database programming is 'don't move the data further than you need to'. It would be many times as efficient to just write "UPDATE porcobrar2012 SET a=b+c+d+...". And you can remove the Class.forName() call too: it hasn't been required for years.