My Sql prepared statement insert avoid duplicate entry - java

I want to insert some data into a table named USERLOGIN and be sure that no duplicate data will be inserted.
I wrote this code as my insert quesry in a java program:
String sql = "INSERT INTO USERLOGIN (" + "deleted," + "loginTime," + "userIpAddress," + "username)" + "VALUES(?,?,?,?)"+ "WHERE "+"? NOT IN (SELECT loginTime FROM USERLOGIN )";
I want to check duplicate entries based on loginTime property.
However when I run my code I got this error: You have an error in your sql syntax
Could you please help me with this problem. I really appreciate that.

use this query :-
String sql = "INSERT INTO USERLOGIN (deleted, loginTime, userIpAddress, username) " + "VALUES(?,?,?,?) " + "WHERE "+"? NOT IN (SELECT loginTime FROM USERLOGIN )";

Related

SQL statement in Java DAO method is not checking if user exists properly

I have DAO method in Java which looks like this:
private boolean validateUser(String email, String username) throws SQLException {
return stmt.execute(
"SELECT NOT EXISTS" +
"(SELECT id from Math_Hub.Users_Information " +
"WHERE username = '" + username + "' OR email = '" + email + "')");
}
The method returns true even if username already exists in database. Why is that?
I tried to test it by hand and the following SQL statement
SELECT NOT EXISTS
(SELECT id from Math_Hub.Users_Information
WHERE username = 'Eren' OR email = 'erenyeager#gmail.com')
This worked perfectly.
NOT EXISTS always return 1 if no row matches in the where clauses. Either use EXISTS or you can go with select query and later check if anything is received in the resultset( select * or select count(*)).

Unknown table 'courses' in field even though the table actually exist in my database

I have two tables, first one is courses table which saved course_id, course_name, course_time, credits... second is selected_course_list table which saved user's courses. The process is that user enter a course_id into Textfield and program will find out the correspond courses information(course_id, course_name, course_time...) then save into user's selected_course_list table.
However I use sql for insert course into select_course_list
The problem is: Actually I create a course table in my database, but the compiler show Unknown table 'courses' in field. Why? BTW, please help me to check whether my insert code is correct or not.
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school_project", "root","");
String sql1 = "INSERT INTO select_course_list(id,course_id,course_class,course_name,course_type,credit,class_time,max,selected) "
+ "SELECT courses.id, courses.course_id, courses.course_class, courses.course_name, courses.course_type, courses.credit, courses.class_time, courses.max, courses.selected"
+ "FROM courses "
+ "WHERE courses.course_id = "+course_code.getText()+" ";
PreparedStatement ps = con.prepareStatement(sql1);
ps.executeUpdate(sql1);
The Compiler show:
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
java.sql.SQLSyntaxErrorException: Unknown table 'courses' in field listjava.sql.SQLSyntaxErrorException: Unknown table 'courses' in field list
Appreciate, but there is another problem.
code:
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school_project", "root","");
String sql1 = "INSERT INTO select_course_list(id,course_id,course_class,course_name,course_type,credit,class_time,max,selected) "
+ "SELECT cs.id, cs.course_id, cs.course_class, cs.course_name, cs.course_type, cs.credit, cs.class_time, cs.max, cs.selected "
+ "FROM courses cs "
+ "WHERE cs.course_id = "+course_code.getText()+"";
PreparedStatement ps = con.prepareStatement(sql1);
ps.executeUpdate(sql1);
The output is
com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value: ''

SQL Delete from two table in Oracle

I have to do remove the row (containing the userId) in the table "USERS". This is my query:
#SqlUpdate("delete from USERS where userId = :userId ")
void removeUser(#Bind("userId") String userId);
But first I want to remove that user from the table "USERS_DATA" (that is a daughter of USERS) which also contain the "userId". How can I do? I've tried this:
#SqlUpdate("delete from USERS_DATA where userId = :userId " +
" and delete from USERS where userId = :userId")
void removeUser(#Bind("userId") String userId);
but console tell me: java.sql.SQLSyntaxErrorException: ORA-00936: missing expression
Unlike some other RDBMS, Oracle does not allow you to pass two statements in the same SQL command (this helps to prevent SQL injection).
You can try using wrapping both queries in an anonymous PL/SLQ block:
BEGIN
delete from USERS_DATA where userId = :userId;
delete from USERS where userId = :userId;
END;
/
This will allow you to execute both DML statements together as they are part of the singular containing PL/SQL block.
Unfortunately, I am not familiar with that annotation syntax in Java so I cannot help you convert it to Java but I would guess at:
#SqlUpdate("BEGIN " +
"delete from USERS_DATA where userId = :userId; " +
"delete from USERS where userId = :userId; " +
"END;")
void removeUser(#Bind("userId") String userId);
Alternatively, you can create a procedure in Oracle:
CREATE OR REPLACE PROCEDURE delete_user(
in_userID USERS_DATA.USERID%TYPE
)
AS
BEGIN
DELETE FROM USERS_DATA WHERE userId = in_userId;
DELETE FROM USERS WHERE userId = in_userId;
END;
/
And you can then just call this procedure.

Syntax SQL error on IF EXISTS statement

in my java project I need to check if a row exists in a table.
In case of exist, I need to Update; if not, I need to create it. The Sql syntax to do this should be:
IF EXISTS(SELECT * FROM table1 WHERE column4='"+int4+"' AND column5='"+int5+"') "
+"BEGIN "
+ "UPDATE table1"
+ "SET column1='"+int1+"', column2='"+int2+"' "
+ "WHERE column4='"+int4+"' and column5='"+int5+"' "
+ "END "
+ "ELSE"
+ "INSERT INTO table1 (column1, column2, column4, column5, column3) "
+ "VALUES ('" + int1 + "',"
+ "'" + int2 + "',"
+ "'" + int4 + "',"
+ "'" + int5 + "',"
+ "'" + int3 +"');
where int1, int2, int3, int4, int5 are integer values.
Well, if I put this code I have an Sql syntax error on my java compiler :
com.mysql.jdbc.exceptions.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 'IF EXISTS(SELECT * FROM table1 WHERE column4='1' AND column5='0') BEGIN UPDATE' at line 1
But I can'y see the error
You've got an error because in MySQL you can't use conditional statement IF other than in stored routines (stored procedure, stored function, trigger).
What you need is so called UPSERT which you can achieve in MySQL with INSERT INTO ... ON DUPLICATE KEY UPDATE. In order for it to work you have to have a UNIQUE INDEX on column4 and column5.
ALTER TABLE table1 ADD UNIQUE (column4, column5);
Now your INSERT statement might look like
INSERT INTO table1 (column1, column2, column4, column5, column3)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE column1=VALUES(column1), column2=VALUES(column2);
Here is SQLFiddle demo
On a side note: Use parameterized queries instead of interpolating query strings. I'm not an expert in Java but I'm sure it has a first class infrastructure for that. Otherwise you are wide open to SQL-injections.

SQL Query in Java - Unable to select two columns

I currently have a search function for my database where I have a Java front-end GUI.
At the moment in Java I have a SELECT statement that checks what one enters is LIKE something. The problem that I am having is that within my SELECT statement, I want to also get the forename column.(I am fairly new to this).
Below is a snippet of the code:
/*
* Search method
*/
public void search()
{
// search function - person query
String sqlPerson = " SELECT * FROM `person` "
+ "WHERE ((`person`.`Surname`LIKE ?) "
+ "OR (`person`.`Forename` LIKE ?) "
+ "OR (`person`.`Person_Id` LIKE ?) "
+ "OR (`person`.`aka` LIKE ?) "
+ ")ORDER BY `person`.`Surname` ASC ";
Does anyone know how I can select both forename and surname so it gets both columns because at the moment when I search, I can only do it by one column (As I am currently using an OR).
Thanks
Your query already gets all colums from that table. What is your problem? Just replace the correct ? with the search term you are looking for.

Categories

Resources