This is my SQL query:
INSERT INTO SomeTable (UniqueID, SomeData, SomeNumber)
VALUES (#unique_id + 1, 'some value', '4234435435')
ON DUPLICATE KEY UPDATE
OtherNum = OtherNum + 1, SomeNumber = '999';
SELECT #unique_id := MAX(UniqueID) FROM SomeTable;
I use MariaDB. And I use HeidiSQL to manage databases, execute queries etc. In HeidiSQL my query works fine, but when I try to execute it in Java I get SQLSyntaxErrorException. Here is how I do it:
Connection connection = DriverManager.getConnection("jdbc:mariadb://localhost:3306/somedb?user=root&password=password");
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("INSERT INTO SomeTable (UniqueID, SomeData, SomeNumber)\n"
+ "VALUES (#unique_id + 1, 'some value', '4234435435')\n"
+ "ON DUPLICATE KEY UPDATE\n"
+ "OtherNum = OtherNum + 1, SomeNumber = '999';\n"
+ "SELECT #unique_id := MAX(UniqueID) FROM SomeTable;");
In the exception info I see it's caused by "SELECT #unique_id := MAX(UniqueID) FROM SomeTable;" line. Here is the full exception info:
Exception in thread "main" java.sql.SQLSyntaxErrorException: (conn:29) 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 'SELECT #unique_id := MAX(UniqueID) FROM SomeTable' at line 4
Why does this happen and how to make it work?
Related
I got this error i am using java and javafx and it is connected to MYsql DB i got this error while excute this statment from java to my sql please help
Got an exception!
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 'update kstds.match SET
kstds.match.Team1Goals=kstds.match.Team1Goals+1 where kst' at line 1
String Query ="use kstds; update kstds.match SET kstds.match.Team1Goals=kstds.match.Team1Goals+1 "
+ "where kstds.match.Team1ID= ( select kstds.team.TeamID from kstds.team where kstds.team.Name='AHLI' ) "
+ "and kstds.match.Matchid = 1 ; "
+ "Update kstds.match SET kstds.match.Team2Goals=kstds.match.Team2Goals+1 "
+ "where kstds.match.Team2ID= ( select kstds.team.TeamID from kstds.team where kstds.team.Name='AHLI' ) "
+ "and kstds.match.Matchid=1;";
you are trying to execute multiple sql queries which should be done using addBatch & executeBatch.
you don't have to execute use kstds because the connection to the database is set via Java
try this:
String Query1 ="update match SET match.Team1Goals=match.Team1Goals+1 "
+ "where match.Team1ID= ( select team.TeamID from team where team.Name='AHLI' ) "
+ "and match.Matchid = 1 ; "
String Query2 ="Update match SET match.Team2Goals=match.Team2Goals+1 "
+ "where match.Team2ID= ( select team.TeamID from team where team.Name='AHLI' ) "
+ "and match.Matchid=1;";
//stmt is your Statement and conn is your Connection
con.setAutoCommit(false);
stmt.addBatch(Query1);
stmt.addBatch(Query2);
stmt.executeBatch();
con.commit();
I want to fetch data from exasol but only facing this issue when I use limit clause in query.
If i hardcode the limit values in query and don't use prepared statement for then it works fine. But when I try to set int for limit clause in prepared statement it gives me exception
public static final String FROM_DWB_DATA = "SELECT * FROM DWB_DATA a \n"
+ "INNER JOIN DWB_CONN b \n"
+ "ON a.SOURCE_ID=b.ID\n"
+ "WHERE b.PROJECT_ID=? ORDER BY a.TABLE_NAME LIMIT ? , ?";
//and in Prepared statement i am setting these values
PreparedStatement ps = getSQLConnection(projectId, conid)
.prepareStatement(FROM_DWB_DATA_TABLE);
ps.setString(1, projectId);
ps.setInt(2, 0);
ps.setInt(3, 2);
java.sql.SQLException: non-negative integer value expected in LIMIT clause
I guess, it adds your values in quoted form: LIMIT '0', '2'.
Try to build query string normally and run it as simple non-prepared query.
Below I show my sql query which is dynamic in Java.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -365);
Adjust to 12 months before current month with 0 hrs and min
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 1, 0, 0, 0);
String lastYearTime = String.valueOf(cal.getTimeInMillis() / 1000);
while(iterator.hasNext())
{
tablename = Database.getTableName((String)iterator.next());
fields = "status,count(*) as count";
query.append("select " + fields + " from " + tablename + " where");
query.append(" toid ='" + collegeId + "'");
query.append(" and dtstamp >='" + lastYearTime + "'");
query.append(" group by status");
if(i.hasNext())
query.append(" UNION ");
}
StringBuffer countquery = new StringBuffer("select status, SUM(count) as count from ( " + query + ")as temp group by status ");
ResultSet rs = Database.executeQuery(countquery.toString(), connection);
In the above query, tablename will be random based on other factors. collegeId can be any id. Status can be like dropout,pursuing or any random status.
When I execute my above query, result set works fine and data is displayed. But when there are no records in the database then it throws a sql syntax error 1064 stating
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 ')as temp group by status' at line 1
Problem1
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 ')as temp group by status' at line 1
You have a problem in your query:
select status, SUM(count) as count from ( " + query + ")as temp group by status
You should to make a space in your query here :
from ( " + query + ")as
replace this ")as with this ") as
EDIT
Problem2
SQL Exception : 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 ') as temp group by status' at line 1 SQL State : 42000 Error Code : 1064
Your query is a String so you should to put it between two 'query'
now replace this :
select status, SUM(count) as count from ( " + query + ")as temp group by status
By this :
select status, SUM(count) as count from ( '" + query + "') as temp group by status
Good luck.
Resultset throws syntax error when there are no records in database
No it doesn't. It throws a syntax-error exception when you have a syntax error in your query.
I have two tables in my database viz linkrecord(URL,NAME) and dishrate(dishname, rate,review). I want to create a 3rd table viz record which contains URL, dishname and rating from the 1st two table,in correspondance with dishname which is common to both table. I have tried the following Insert query but it shows the 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 '.NAME = dishrate.dishnameORDER BY dishrate.rate DESC' at line 1"
The query is:
String query= "INSERT INTO crawler.record (URL, Dishname, rate)"+
"SELECT linkrecord.URL, dishrate.dishname,dishrate.rate"+
"FROM linkrecord, dishrate"+
"WHERE linkrecord.NAME = dishrate.dishname"+
"ORDER BY dishrate.rate DESC";
Statement stmt=db.conn.createStatement();
stmt.executeUpdate(query);
I am unable to find the error in the above query.What should I do? Thank You
You forget the spaces and you ended up with query parts like:
INSERT INTO crawler.record (URL, Dishname,rate)<space missing here>SELECT
Correct way is:
String query= "INSERT INTO crawler.record (URL, Dishname, rate) "+
"SELECT linkrecord.URL, dishrate.dishname,dishrate.rate "+
"FROM linkrecord, dishrate "+
"WHERE linkrecord.NAME = dishrate.dishname "+
"ORDER BY dishrate.rate DESC";
I use Java to do some SQL queries.
in general the queries that i want to perform are:
set #uid=?; set #friendsList=?; IF EXISTS(select 1 from fb_user_friends join fb_user on " +
" fb_user.id = fb_user_friends.fb_user_id where uid=#uid) then " +
"update fb_user_friends set friends = #friendsList; ELSE insert " +
"into fb_user_friends(fb_user_id,friends) values(#uid,#friendsList); END IF;
I get the MySQL Connection using:
Class.forName("com.mysql.jdbc.Driver").newInstance();
this._sqlconn = DriverManager.getConnection(this._url,this._userName,this._password);
and I try to execute the following code:
String sql="set #uid=?; set #friendsList=?; IF EXISTS(select 1 from fb_user_friends join fb_user on " +
" fb_user.id = fb_user_friends.fb_user_id where uid=#uid) then " +
"update fb_user_friends set friends = #friendsList; ELSE insert " +
"into fb_user_friends(fb_user_id,friends) values(#uid,#friendsList); END IF;";
try {
PreparedStatement stmt = this._sqlconn.prepareStatement(sql);
stmt.setLong(1,uid);
stmt.setString(2,StringUtils.join(friendsList.toArray(), ','));
stmt.executeUpdate();
}catch (SQLException e) ....
I get the exception:
class 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 'set #friendsList='110633,2018837,6813007,8803501,10711399,500061635,500214841,50'
can't I run several commands with prepareStatement ?
Do i need to find a different approach to set the MySQL variables uid and friendsList?
Thanks!
That looks a bit like a mysql stored procedure to me? If I'm not mistaken, you should register that in mysql directly. That way, you're able to call it using your prepared statement.