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.
Related
I want to insert the SUM of Somme_versee (column in table Versement) in the column Versement_total.
This is a part of my code:
statement.executeUpdate("INSERT INTO Versement ( Nom , Prenom, Date , Somme_versee,Prix_du_logement, Nom_du_projet) VALUES('" + nom.getText() +"','" +prenom.getText() +"','" +date.getText() + "'," + verse.getText() + ", " + "(SELECT Prix_du_logement FROM Client WHERE Nom='"+ nom.getText() +"' AND Prenom='"+ prenom.getText() + "')," + " (SELECT Nom_du_projet FROM Client WHERE Nom='" + nom.getText()+ "' AND Prenom='" +prenom.getText() + "'))");
statement.executeUpdate("UPDATE Versement SET Versement_total= SUM(Somme_versee) " );
When executing I get this error: misuse of aggregate function SUM()
You should never do this in the same table. And it will get worse when the table gets more records. But what you seem to want is:
UPDATE Versement SET Versement_total = (SELECT SUM(Somme_versee) FROM Versement)
I am new to Java and MYSql in fact using this combination first time and facing real trouble. I want to insert few records in a table but unable to do so. Following are the fields and datatype in the table named tbl_cdr in MySql.
**Field** **Type**
DATEANDTIME datetime NULL
VALUE1 int(50) NULL
VALUE2 varchar(50) NULL
VALUE3 varchar(50) NULL
VALUE4 varchar(50) NULL
VALUE5 varchar(50) NULL
The record I want to insert contains following values
2014-05-19 02:37:18, 405, MGW190514023718eab4, 923016313475, IN, ALERTSC
I am using following query and statements to Insert record in table
sqlQuery = "INSERT INTO tbl_cdr (DATEANDTIME,VALUE1,VALUE2,VALUE3,VALUE4,VALUE5)" + "VALUES ("+ forDateAndTime.format(date) + ", " + columnsList.get(1) + ", " + columnsList.get(2) + ", " + columnsList.get(3) + ", " + columnsList.get(4) + ", " + columnsList.get(5) + ")";
try
{
Statement qryStatement = conn.createStatement();
qryStatement.executeUpdate(sqlQuery);
qryStatement.close();
} catch (SQLException ex)
{
Logger.getLogger(CdrProject.class.getName()).log(Level.SEVERE, null, ex);
}
But when I reach the statement qryStatement.executeUpdate(sqlQuery); exception is thrown as:
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 '02:37:18, 405, MGW190514023718eab4,
923016313475, IN, ALERTSC)' at line 1
value2 ,value3 ,value4 and value 5 are varchars so it should be written within ''.
Do like this
sqlQuery = "INSERT INTO tbl_cdr (DATEANDTIME,VALUE1,VALUE2,VALUE3,VALUE4,VALUE5)" + "VALUES ("+ forDateAndTime.format(date) + ", " + columnsList.get(1) + ", '" + columnsList.get(2) + "',' " + columnsList.get(3) + "',' " + columnsList.get(4) + "',' " + columnsList.get(5) + "')";
You're inserting the date incorrectly. MySQL allows you to insert a string literal or a number.
You're trying to use 02:37:18 as a number, when really you should be using it as a string literal: '02:37:18'
Here is the MySql Reference describing this.
You're also not treating your varchars as strings either, they should be enclosed with quotes.
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 )";
How can i manually insert values if not exist...i tried following code but it produce error.How can i insert values if not exist in the table
String sql1 = "CREATE TABLE IF NOT EXISTS admin " +
"(id INTEGER not NULL AUTO_INCREMENT, " +
" user_name VARCHAR(255), " +
" password VARCHAR(255), " +
" isAdmin BOOLEAN NOT NULL DEFAULT '0', " +
" memo VARCHAR(255), " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql1);
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
stmt.executeUpdate(insert);
it produce an error like
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 'IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'mem' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
should be
String insert="INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
MySQL (and any other SQL implementation as well) doesn't support IF NOT EXISTS in INSERT queries.
your INSERT query must be
"INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo) VALUES (1,'admin','admin',1,'memo')"
What you want may be INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE....
The former will update an existing row if a duplicate insert is detected, while the latter will just throw away duplicate inserts.
In both cases, you'll have to create a UNIQUE constraint on the column you want to check for duplicates. If the UNIQUE is violated, the alternate function is invoked.
I am getting the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'userId' in 'field list'
The code which is causing this error is this:
PreparedStatement pstmt =
con.prepareStatement(
"INSERT INTO " +
tableName +
" (userId,username,email,password) VALUES (?,?,?,?)");
My table gets created by the following command
stmt.executeUpdate(
"CREATE TABLE " +
tableName +
" (" +
" userId INT, " +
" userName VARCHAR(255) NOT NULL, " +
" email VARCHAR(255) NOT NULL, " +
" password VARCHAR(255), " +
" PRIMARY KEY(userId)" +
" )");
stmt.close();
Can someone help me spot my mistakes if any. I am a novice in this so I am kind of struggling to find where exactly the error is.
The error was because there already existed another table with the same table name.
One other thing to look at is triggers. I was getting the same error and eventually determined that the error was the result of a trigger statement rather than the insert statement. The "unknown column" was in a table the trigger was trying to insert into.
If you are using insert statement and there is column value missing or empty. It can give this error. I was using prepared statement. I got this error for a column having numeric data type. The root cause of this was empty string being passed as column value. Strangely it throws "unknown column" e