I am trying to search my database using mySQL through JDBC. When I use this statement:
SELECT * FROM tablename WHERE name='joe';
It does a case insensitive search and returns any rows that have 'Joe' or 'joe', which is what I want. I ran select collation(version()), and this returned 'utf8_general_ci', which is apparently supposed to be case insensitive. However, when I run the same query using JDBC within my Java applet, it does a case sensitive search. Here is my query2 function:
try {
Vector<Vector<String>> out = new Vector<Vector<String>>() ;
Connection con = connect() ;
Statement statement = con.createStatement() ;
System.out.println( "SQL: " + s ) ;
ResultSet rs = statement.executeQuery(s) ;
while( rs.next() )
{
String r = rs.getString(1) ; // RS is indexed from 1
Vector<String> q = new Vector<String>() ;
for( int i = 2 ; i <= tableSize ; i ++ )
{
q.add(r) ;
r = rs.getString(i) ;
}
q.add(r) ;
out.add(q) ;
}
con.close() ;
return( out ) ;
} catch (SQLException e) {
System.err.println( "SQL EXCEPTION" ) ;
System.err.println( s ) ;
e.printStackTrace();
}
And here is my select function that calls query2:
public static Vector<Vector<String>> select( String table , List<String> columns , List<String> values )
{
String statement = "SELECT * from `" + table + "` WHERE " ;
for( int i = 0 ; i < columns.size(); i ++ )
{
statement += columns.get(i) + "='" + values.get(i) + "'" ;
if( i + 1 < columns.size() )
statement += " AND " ;
}
statement += " ;" ;
return query2 ( statement , tableSize(table) ) ;
}
Any idea how I can make this query case insensitive?
It turns out that the search I thought was using the select function was actually using a different function. This function was selecting everything from the database and sorting through it client-side. I tested the select function and it actually is case insensitive, without having to use any of the tips given (but thanks for the advice!).
Wouldn't this line need to read
statement += "UPPER("+columns.get(i) + ")='UPPER(" + values.get(i) + ")'"
downfall... can't use indexes since it's uppering everything.
Related
I have the following JSON List: '["Foo","Bar"]'
The following entries are in my MySQL table t
Name | Color
--------------
Foo | Red
Bar | Blue
Foobar | Green
Is there a way to use my JSON List as a condition in my where clause and get the same result like:
select * from t where name in ('Foo','Bar')
?
Akina solved it:
SELECT * FROM t WHERE JSON_CONTAINS( '["Foo","Bar"]', CONCAT('"', Name, '"') )
From my knowledge you can put multiple WHERE statements on a SQL query
See: https://www.w3schools.com/SQl/sql_where.asp
you just need to add a 'AND' or 'OR' after each condition
SELECT * FROM Customers
WHERE Country='Mexico'
AND Address='Avda. de la Constitución 2222'
OR Address='Mataderos 2312';
;
So you just build the string you need before using
with c# you can do something like (just AND operators):
public List<Data> ExecuteQueryAND(List<string> statements, string table)
{
// initial connection
// ...
string str = $"SELECT * FROM {table}\n";
for (int i =0; i > statements.Count; i++)
{
if( i == 0 )
{
str = str + $"WHERE {statements[i]}\n";
}
str = str + $"\tAND {statements[i]}\n";
}
str = str + ";";
Console.WriteLine("Sql Query: " + str);
// more code to execute sql
}
then when you call it:
// some code ..
FilterList = ExecuteQueryAND( new List<string> { "Access=\"ADMIN\""});
// more code ..
I am creating a Java application that communicates with MySQL database. Using XAMPP 5.6.33-0 and phpMyAdmin. I have the following method that, among other values, inserts a Timestamp into the table RATING:
PreparedStatement pst = myConn.prepareStatement("INSERT INTO RATING
(ratingDate) VALUES(?)");
java.util.Date today = new java.util.Date();
Timestamp ts = new java.sql.Timestamp(today.getTime());
pst.setTimestamp(1, ts);
pst.executeUpdate();
The schema of the RATING relation looks as follows:
CREATE TABLE RATING
(cID INT,
rID INT,
stars INT,
ratingDate TIMESTAMP,
FOREIGN KEY(cID) REFERENCES CUSTOMER(cID) on delete cascade,
FOREIGN KEY(rID) REFERENCES ROOM(rID)
) ;
So attribute ratingDate is defined as Timestamp. Everything works great except when the Timestamp is inserted its value is always set to all zeros: 0000-00-00 00:00:00
I tried converting the Timestamp to string using t.toString and can clearly see that the Timestamp object is created properly. It seems the problem is with setTimestamp() method. Also, converting the data type of ratingDate to just Date and using setDate() method works fine, but setTimestamp() function always sets the attribute value to all zeros.
There are, of course, workaround for this. I could declare the date as varchar, convert Timestamp to a String and insert it using setString() but I am really wondering what the problem may be. Running Eclipse with Tomcat server. No errors in console.
Thank you in advance for any help, I'd be happy to provide any other necessary information.
Avoid legacy date-time classes
The all-zeros values is a mystery. But I can tell you that you are using terrible date-time classes that were supplanted years ago by the java.time classes with the adoption of JSR 310. This is making your work more complicated than it needs to be.
I suggest creating a simple dummy table to narrow down your problem.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime ) ;
Example app
I do not use MySQL. But here is a complete example app using the H2 Database Engine.
package work.basil.example;
import org.h2.jdbcx.JdbcDataSource;
import java.sql.*;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class H2DateTimeExample
{
public static void main ( String[] args )
{
H2DateTimeExample app = new H2DateTimeExample ();
app.demo ();
}
private void demo ( )
{
JdbcDataSource dataSource = new JdbcDataSource ();
dataSource.setURL ( "jdbc:h2:mem:offsetdatetime_example_db;DB_CLOSE_DELAY=-1" ); // Set `DB_CLOSE_DELAY` to `-1` to keep in-memory database in existence after connection closes.
dataSource.setUser ( "scott" );
dataSource.setPassword ( "tiger" );
// Create table.
String sql = "CREATE TABLE person_ ( \n" +
" pkey_ UUID NOT NULL DEFAULT RANDOM_UUID() PRIMARY KEY , \n" +
" name_ VARCHAR NOT NULL , \n" +
"first_contacted_ TIMESTAMP WITH TIME ZONE NOT NULL " +
") ;";
// System.out.println ( sql );
try (
Connection conn = dataSource.getConnection () ;
Statement stmt = conn.createStatement () ;
)
{
stmt.execute ( sql );
} catch ( SQLException e )
{
e.printStackTrace ();
}
// Insert row.
sql = "INSERT INTO person_ ( name_ , first_contacted_ ) \n";
sql += "VALUES ( ? , ? ) \n";
sql += ";";
try (
Connection conn = dataSource.getConnection () ;
PreparedStatement pstmt = conn.prepareStatement ( sql , Statement.RETURN_GENERATED_KEYS ) ;
)
{
OffsetDateTime odt = OffsetDateTime.now ( ZoneOffset.UTC );
pstmt.setString ( 1 , "Jesse Johnson" );
pstmt.setObject ( 2 , odt );
pstmt.executeUpdate ();
ResultSet rs = pstmt.getGeneratedKeys ();
// System.out.println( "INFO - Reporting generated keys." );
// while ( rs.next() ) {
// UUID uuid = rs.getObject( 1 , UUID.class );
// System.out.println( "generated keys: " + uuid );
// }
} catch ( SQLException e )
{
e.printStackTrace ();
}
// Query table.
sql = "TABLE person_ ;";
try (
Connection conn = dataSource.getConnection () ;
PreparedStatement pstmt = conn.prepareStatement ( sql ) ;
)
{
try ( ResultSet rs = pstmt.executeQuery () ; )
{
while ( rs.next () )
{
UUID pkey = rs.getObject ( "pkey_" , UUID.class );
String name = rs.getString ( "name_" );
OffsetDateTime firstContacted = rs.getObject ( "first_contacted_" , OffsetDateTime.class );
System.out.println ( "pkey: " + pkey + " | name: " + name + " | firstContacted: " + firstContacted );
}
}
} catch ( SQLException e )
{
e.printStackTrace ();
}
System.out.println ( "Done." );
}
}
When run.
pkey: b14fd25f-1598-4f09-9475-83ac5967a338 | name: Jesse Johnson | firstContacted: 2019-07-28T02:10:07.731005Z
Done.
After some additional research I figured it out. The problem was that the java Timestamp object uses milliseconds at the end while the timestamp attribute in the MySQL table didn't (it was in the format "yyyy-MM-dd HH:mm:ss"). So this mismatch prevented the insertion of the correct timestamp and instead put a tuple with all zeros into MySQL table. The solution is to format the Timestamp object in the java code to cut off the milliseconds and then insert the Timestamp object into MySQL table:
java.util.Date today = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(today.getTime());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
pst.setObject(4, formatter.format(timestamp));
This worked like a charm. Hope it helps somebody!
This has been driving me crazy and I'm sure it's something simple. I'm getting a 'values must contain at least one element' error from server when I try to input a reservation from the table that comes up. It's all running ok. No matter if I use quotes in the VALUES section or plus(+)symbols or quotes over the separating commas I get different error messages. When I put quotes over table_num I get and error telling me that you cant insert CHAR into INTEGER. When I remove quotes I get error telling me -
Severe: java.sql.SQLSyntaxErrorException: Column 'TABLE_NUM' is either not in any table in the FROM list or appears within a join specification etc. Could anyone tell me what is going on? Here's the jsp code. Thanks in advance.
<%
int tableNum = 0;
String firstName = null;
String lastName = null;
String Address = null;
int Phone = 0;
java.sql.Date date = null;
int People = 0;
if (request.getParameter("table_num")!=null){
tableNum = Integer.parseInt(request.getParameter("table_num"));
}
if (request.getParameter("first")!=null){
firstName = request.getParameter("first");
}
if (request.getParameter("last")!=null){
lastName = request.getParameter("last");
}
if (request.getParameter("address")!=null){
Address = request.getParameter("address");
}
if (request.getParameter("phone")!=null){
Phone = Integer.parseInt(request.getParameter("phone"));
}
if (request.getParameter("date")!=null){
java.util.Date utilDate = new java.util.Date(request.getParameter("date"));
date = new java.sql.Date(utilDate.getTime());
}
if (request.getParameter("people")!=null){
People = Integer.parseInt(request.getParameter("people"));
}
if(tableNum != 0 && firstName != null && lastName != null && Address != null && Phone != 0 && date != null && People != 0){
String URL = "jdbc:derby://localhost:1527/Reservations";
String USERNAME= "johnpaul";
String PASSWORD= "purlease";
Connection myCon = null;
Statement ste = null;
PreparedStatement preparedStmt = null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println("Connecting to DB...");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Reservations","johnpaul", "purlease");
System.out.println("Connected successfuly");
System.out.println("Inserting records into table");
Statement st = con.createStatement();
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS(TABLE_NUM,FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE,DATE,NUMBER_IN_PARTY)VALUES(table_num,first,last,address,phone,date,people)";
st.executeUpdate (query);
System.out.println("Records inserted");
}catch(SQLException se){
se.printStackTrace();
}catch(ClassNotFoundException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
%>
Your problem appears to be here:
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (table_num, first,last,address,phone,date,people)";
Two things here:
1. Escape your strings; and
2. Concatenate the values in your variables to the string.
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (" + table_num + ", '" + first + "', '" + last + "', '" + address + "', " + phone + " , '" + date + "', " + people + ");";
You may have to verify the format that your database engine expects the date field.
I have a jersey java server and a mysql server:
I send a POST with an ArrayList<Long> to the server. Then I want to do a select like ...where long OR long OR long....
Is there an elegant way to solve this problem and not to do always a single select in a for loop?
How can I form a sql-statement with dynamic count of where clauses?
Thank you very mutch.
Instead of OR multiple times, you can use IN with the where clause in the SQL query.
You can read ArrayList object in a loop and set the where clause values.
JAVA code snippet:
int paramCount = list.size();
StringBuilder sqlSelect = new StringBuilder( 1024 );
sqlSelect.append( "select x,y,z from my_table " );
if( paramCount > 0 ) {
sqlSelect.append( "where long_column in ( " );
for( i = 0; i < paramCount; i++ ) {
sqlSelect.append( ( i > 0 ? ", ?" : "?" );
} // for each param
sqlSelect.append( " )" );
} // if list is not empty
// make the prepare statement (pst) with the above sql string
// ...
// now set the parameter values in the query
int paramIndex = 1;
if( paramCount > 0 ) {
for( i = 0; i < paramCount; i++ ) {
pst.setLong( paramIndex++, ( (Long)list.get( i ) ).longValue() );
} // for each param
} // if list is not empty
i've got some code that is triggering a syntax error because of some misplaced semicolons. if this was running on the command line, i'd solve this with a delimiter. unfortunately, the jdbc4 driver doesn't seem to recognize delimiters. anyway to get this to run?
delimiter |
CREATE TRIGGER obs_update BEFORE UPDATE ON obs
FOR EACH ROW
BEGIN
IF OLD.voided = 0 AND NEW.voided = 1 THEN
DELETE FROM clinic_obs WHERE id = OLD.obs_id;
ELSE
UPDATE clinic_obs SET clinic_obs.revision_token = NOW()
WHERE NEW.obs_id = clinic_obs.id;
END IF;
END;
|
delimiter ;
Delimiter is a command for SQL client. There is no need to use delimiter in JDBC.
Example below shows it:
import java.sql.*;
public class TriggerExample {
public static void main(String args[]) {
String connectionURL = "jdbc:mysql://localhost:3306/test";
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(connectionURL, "login",
"password");
Statement stmt = con.createStatement();
stmt.execute("CREATE TRIGGER obs_update BEFORE UPDATE ON obs "
+ "FOR EACH ROW "
+ "BEGIN "
+ "IF OLD.voided = 0 AND NEW.voided = 1 THEN "
+ " DELETE FROM clinic_obs WHERE id = OLD.obs_id; "
+ "ELSE "
+ " UPDATE clinic_obs SET clinic_obs.revision_token = NOW() "
+ " WHERE NEW.id = clinic_obs.id; "
+ "END IF; "
+ "END;");
con.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
Try removing the semi colon after the final END word. so it looks like this:
delimiter |
CREATE TRIGGER obs_update BEFORE UPDATE ON obs
FOR EACH ROW
BEGIN
IF OLD.voided = 0 AND NEW.voided = 1 THEN
DELETE FROM clinic_obs WHERE id = OLD.obs_id;
ELSE
UPDATE clinic_obs SET clinic_obs.revision_token = NOW()
WHERE NEW.obs_id = clinic_obs.id;
END IF;
END|
It should work because I have done a similar trigger/procedure using jdbc driver.