Set Time Zone on MYSQL session - mysql

I am attempting to use the following "Select" statement to set the Session TimeZone before selecting from a Table. The Code below gives me the following exception when executed:
"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 'Select IsActive, HID as EmpNum, NameFirst, NameLast, FROM_UNIXTIME(timeIn) as Ti' at line 1"
Here is the Select statement in context:
private static List<EventLog> getTimeIPEventLog(String date) throws ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException {
final String sql =
"SET time_zone='UTC'; Select IsActive, HID as EmpNum, NameFirst, NameLast, FROM_UNIXTIME(timeIn) as TimeIn, FROM_UNIXTIME(timeOut) as TimeOut, ##session.time_zone TimeZone, ##global.time_zone\n" +
"from eventLog el\n" +
"join users u\n" +
"on (u.usersID = el.usersID)\n" +
"where Date(FROM_UNIXTIME(timeIn)) = '" + date + "'\n" +
"order by timeIn desc";
String url = MainApp.HRMSApplicationProperties.getProperty("timeIPJDBCString") + "?user=" + MainApp.timeIPCredentials.getKey() + "&password=" + MainApp.timeIPCredentials.getValue();
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection(url + "&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
List<EventLog> list = FXCollections.observableList(new ArrayList<>(0));
while (resultSet.next()) {
list.add(new EventLog(resultSet.getString("EmpNum"), resultSet.getString("NameFirst"), resultSet.getString("NameLast"), resultSet.getTimestamp("TimeIn"), resultSet.getTimestamp("TimeOut"), resultSet.getString("TimeZone")));
}
return list;
}
I appreciate your assistance

Related

How to correctly display in class data from joined sql tables?

I've started to learn SQL, I'd appreciate some insight and help on the below issue. My task is to: write a query in SQL workbench which returns names and surnames of users with more than 2 posts written (the query copied below). This part seems to work fine.
Then display in test class in a loop names and surnames of users that have published at least 2 posts.
How to write a code that creates that query in the test class? Basically I get syntax error and I'm not sure how it should look like("Column 'POSTS_NUMBERS' not found.").
(then another part of exercise follows - add posts and then check by assertion if the actual number of records in the data base is the same as result of the query)
SELECT USERS.FIRSTNAME, USERS.LASTNAME, USERS.ID, COUNT(*) AS POSTS_NUMBER
FROM USERS
JOIN POSTS ON USERS.ID = POSTS.USER_ID
GROUP BY POSTS.USER_ID
HAVING COUNT(*) >= 2;
#Test
public void testSelectUsersAndPosts() throws SQLException {
//given
DbManager dbManager = DbManager.getInstance();
String countQuery = "SELECT COUNT(*) FROM USERS"; //IS THIS PART CORRECT?
Statement statement = dbManager.getConnection().createStatement();
ResultSet rs = statement.executeQuery(countQuery);
int count = 0;
while (rs.next()) {
System.out.println(rs.getInt("POSTS_NUMBERS") + ", " +
rs.getString("FIRSTNAME") + ", " +
rs.getString("LASTNAME"));
}
String sql = "INSERT INTO POSTS(USER_ID, BODY) VALUES ('3', 'I am Mark')";
statement.executeUpdate(sql);
sql = "INSERT INTO POSTS(USER_ID, BODY) VALUES ('3', 'hey!')";
statement.executeUpdate(sql);
//when
String sqlQuery = "SELECT * FROM USERS";
statement = dbManager.getConnection().createStatement();
rs = statement.executeQuery(sqlQuery);
//then
int counter = 0;
while (rs.next()) {
System.out.println(rs.getInt("USERS.ID") + ", " +
rs.getString("FIRSTNAME") + ", " +
rs.getString("LASTNAME"));
counter++;
int expected = count + 1;
Assert.assertEquals(expected, counter);
rs.close();
statement.close();
}
}

You have an error in your SQL syntax (...) near ;

I got this message, and I couldn't find any error:
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 'where id ='null'' at line 1
I assumed this code was wrong, but it turned out it isn't.
ResultSet rs = stmt.executeQuery("select password" +
"from userinfo where id = '" + id + "';");
This is full code of error file.
private boolean checkLoginInfo(String id, String password) throws ServletException
{
Connection conn = null;
Statement stmt = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/webdb", "root", "1234");
if (conn == null)
throw new Exception("can't connect to database.<BR>");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select password" +
" from userinfo where id = '" + id + "';");
if (!rs.next())
return false;
String correctPassword = rs.getString("password");
if (password.equals(correctPassword))
return true;
else
return false;
}
There is a missing space between password and from:
select password" + "from userinfo where id = '" + id + "';"
Try this:
"SELECT password FROM `userinfo` WHERE id = '"+id+"'"
You should furthermore read about:
Escaping SQL queries
Authentication/Authorization (why do you select the password only?)
Code formatting
Edit 1:
The error messages tells us, you are setting the id to 'null' (String, because of ''), not NULL. If your id is expecting an Integer, but you are providing a String, it will break.

Matching on empty strings, not nulls, in a MySQL column

I can't get the right syntax - I'm trying to match on the column as an empty string, not a null. I've tried delimiting the string all number of ways, using single double quotes.
containerRefNo = "\"\"";
ps = getConnection().prepareStatement(
"delete from inumber_join where container_no = ?");
The error I receive is
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'from inumber_join where container_no = '""''
When using a parameterized query you don't need to include any delimiters in the parameter value. Simply using ps.setString(1, ""); works fine for me.
That is, ...
// setup
try (Statement st = conn.createStatement()) {
st.executeUpdate(
"CREATE TEMPORARY TABLE inumber_join_temp (" +
"id INT AUTO_INCREMENT, " +
"container_no VARCHAR(10) NULL, " +
"PRIMARY KEY (id)" +
")");
st.executeUpdate(
"INSERT INTO inumber_join_temp (container_no) " +
"VALUES (null), (''), (null), (''), (null)");
}
// test
String sql =
"SELECT COUNT(*) AS n " +
"FROM inumber_join_temp " +
"WHERE container_no = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, ""); // search for empty string
try (ResultSet rs = ps.executeQuery()) {
rs.next();
System.out.println(rs.getInt(1));
}
}
... returns
2

How to insert data to a sqlite database with table name as variable

I would like to insert data into my sqlite data base but with a variable as the name of the table where the data should be entered.
try {
Random rand = new Random();
uniqueID = rand.nextInt(9998) + 1; //Generates a random number from 1 - 9999 inclusively
String dateStart = day1.getText() + "/" + month1.getText() + "/" + year1.getText();
String dateEnd = day2.getText() + "/" + month2.getText() + "/" + year2.getText();
String projectN = projectName.getText();
String addr = address.getText();
//String engineerN = engineerName.getText();
//String engineerP = engineerPassword.getText();
Class.forName("org.sqlite.JDBC");
conn2.setAutoCommit(false);
PreparedStatement ps = conn2.prepareStatement("insert into "My table name" (uniqueid,name,address,startingdate,estcompletion) values(?,?,?,?,?,?)");
ps.setInt(1, uniqueID);
ps.setString(2, projectN);
ps.setString(3, addr);
ps.setString(4, dateStart);
ps.setString(5, dateEnd);
//ps.setString(6, engineerN);
ps.execute();
ps.close();
conn2.commit();
conn2.close();
}
catch ( Exception e1) {
System.err.println( e1.getClass().getName() + ": " + e1.getMessage() );
System.exit(0);
}
}
}
public String JJI() {
return projectName.getText();
}
}
"My table name" in the prepared statement is the place where I want to put my table name getting it from projectName.getText(); at the end. The user enters projectname.getText in another class.
Thank you for the help!
Store your table name in a String variable (how you like): String tableName = "users";
Make a query variable that contains your SQL query:
String query = "insert into '" + tableName + "' (uniqueid,name,address,startingdate,estcompletion) values(?,?,?,?,?,?)";
If you would like to have variables to insert, replace the "?" with your variable names as you have done in your code:
ps.setInt(1, uniqueID);
ps.setString(2, projectN);
ps.setString(3, addr);
ps.setString(4, dateStart);
ps.setString(5, dateEnd);
Execute the query:
PreparedStatement ps = conn2.prepareStatement(query);
ps.execute();

JDBC4/MySQL syntax error: when retrieving data from mysql table

Is there anything wrong in the code below?
String sql = "SELECT username, password FROM REGCUSTOMERS" + "WHERE username = ? AND password = ?";
I'm trying to get the data from the username and password column of REGCUSTOMERS table.
Eclipse Error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '= ? AND password = ?' at line 1
private boolean isAuthenticated(String userid, String password) {
// JDBC logic to verify from database.
try {
Class.forName(driverName);
Connection conn = null;
PreparedStatement st = null;
String sql = "SELECT username, password FROM REGCUSTOMERS" + "WHERE username = ? AND password = ?";
conn = DriverManager.getConnection(databaseURL, USERNAME, PASSWORD);
st = conn.prepareStatement(sql);
ResultSet rs = st.executeQuery(sql);
if (rs.getString("username") != userid && rs.getString("password") != password) {
return false;
}
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
You have no space between REGCUSTOMERS and WHERE. Add the space and you should be fine:
String sql = "SELECT username, password FROM REGCUSTOMERS " + "WHERE username = ? AND password = ?";
This part:
... FROM REGCUSTOMERS" + "WHERE username ...
Will result in the following SQL:
FROM REGCUSTOMERSWHERE
That of course is wrong.
The + doesn't make sense there, but if you want it, you need a space at least on one side
"... FROM REGCUSTOMERS " + "WHERE username ..."