I'm trying to create a procedure from the MySQL API in C. My query string is as follows (in the C code):
"CREATE PROCEDURE clockOut (taskID INT UNSIGNED) "
"BEGIN "
"DECLARE #username VARCHAR(8);"
"SELECT #username = userID FROM TaskItem WHERE id=taskID;"
"UPDATE TaskItem SET onClock=0,stopTime=NOW() "
"WHERE id=taskID AND userID=#username;"
"END"
This string will ultimately be transmitted with mysql_query(), which returns error code 1064, a syntax error. What have I done wrong?
As #alk suggested, I removed the # syntax from my variables, and it worked fine.
Related
This is my code. I'm unable to execute it.
This is the error message I get on the $db->execute(); line:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined'
$query = "UPDATE gateway_devices "
."SET coin_lat=:coin_lat, coin_lng=:coin_lng"
."WHERE nick_name=:nick_name AND gateway_id=:g_id AND device_id=:d_id";
$db->query($query);
$db->bind(':coin_lat', $coin_lat);
$db->bind(':coin_lng', $coin_lng);
$db->bind(':nick_name', $nick_name);
$db->bind(':g_id', $g_id);
$db->bind(':d_id', $d_id);
$db->execute();
all i had to do was add a space on line 2 before closing the double quote.
this is how the query looks like before and after adding the whitespace.
before - "UPDATE gateway_devices SET coin_lat=:coin_lat, coin_lng=:coin_lngWHERE nick_name=:nick_name AND gateway_id=:g_id AND device_id=:d_id"
after - "UPDATE gateway_devices SET coin_lat=:coin_lat, coin_lng=:coin_lng WHERE nick_name=:nick_name AND gateway_id=:g_id AND device_id=:d_id"
I am getting a syntax error in the following lines. I am not familiar with mysql so any pointers will be helpfull
ps = con.prepareStatement("INSERT INTO order(status,ordered_on,total_price,user_id) "
+ " VALUES(?,?,?,?)");
ps.setString(1,"pending");
ps.setTimestamp(2,date);
ps.setDouble(3,total_price);
ps.setInt(4,ID);
The error was
MySQL server version for the right syntax to use near 'order(status,ordered_on,total_price,user_id) VALUES('pending','2017-03-22 04:08' at line 1
The problemis that order is a reserved keyword for mysql ; so you have two solutions at your disposal
1 : if you are required some raison to use that work in case you case use backtick escapes `order`
2 : you can use plural for the tables name like orders
ps = con.prepareStatement("INSERT INTO `order`(status,ordered_on,total_price,user_id) "
+ " VALUES(?,?,?,?)");
ps.setString(1,"pending");
ps.setTimestamp(2,date);
ps.setDouble(3,total_price);
ps.setInt(4,ID);
This is q link to the mysal reserved keywords
I created 5 tables in mysql workbench 5.7 in which I will pull data from APIgraph queries for a given facebook page.
However, when I run the code, it throws an error:
ProgrammingError: 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 '%s, %s)' at line 1
Here is the part of the code which I think contains the error :
#create connection to db
connection = connect_db()
cursor = connection.cursor()
#SQL request for inserting the date of the page into the database
insert_page = ("INSERT INTO page"
"(fb_id, name)"
"VALUES (%s, %s)")
insert_posts = ("INSERT INTO posts "
"(page_id, fb_post_id, message, time_created)"
"VALUES (%s, %s, %s, %s)")
And I finally put the data at the end of the code:
cursor.execute(insert_page, json_pageiddata)
Any ideas? Thanks for helping
EDIT: here is my json_pageiddtata variable, obtained from a URL query with APIgraph:
pageid_url = create_pageid_url(current_page, APP_ID, APP_SECRET)
json_pageiddata = render_to_json(pageid_url)
print json_pageiddata["name"], json_pageiddata["id"]
If you are using data as dictionary u need to specify index name, try to use %(name)s.
In the syntax of load infile data i saw that the fields and line clauses are optional. So I used only character set clause for utf8
Here my sql:
cmd = new MySqlCommand("LOAD DATA INFILE " + filename + " INTO TABLE " + tblname + " CHARACTER SET 'UTF8'", conn);
filename is the addresse it's format is: "E:\Macdata\20131228\atelier.sql"
table name is directly taken from database is as : "atelier"
But I get the 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 'E:\Macdata\20131228\atelier.sql INTO TABLE atelier CHARACTER SET 'UTF8'' at line 1
What is the mistake in my query command ?
MYSQLversion is 5.0.10 with XAMPP
After changing the query I begin to receive fatal error number 0 (enclosed filename with ')
cmd = new MySqlCommand("LOAD DATA LOCAL INFILE '" + filename + "' IGNORE INTO TABLE " + tblname + " CHARACTER SET UTF8", conn);
My data file has this form which works on phpmyadmin
INSERT INTO `atelier` VALUES(1, 'Chateau Carbonnieux -1', '2013-12-26', 23, 10, 0, '4 macarons differents', 'mamie', '2013-12-15 11:09:14', 'sabrina', '2013-12-18 05:29:26');
As the error says, your statements is wrong. Quotes are missing in your first statement (see second statement). Check the syntax here:
http://dev.mysql.com/doc/refman/5.6/en/load-data.html
Some sparse notes:
0 is not a fatal error, it's the code for success.
IGNORE handles duplicate rows, not syntax errors.
In the following routine that I found here:
ALTER PROCEDURE [dbo].[usp_RethrowError]
AS -- Return if there is no error information to retrieve.
IF ERROR_NUMBER() IS NULL
RETURN;
DECLARE #ErrorMessage NVARCHAR(4000),
#OriginalErrorNumber INT,
#RethrownErrorNumber INT,
#ErrorSeverity INT,
#ErrorState INT,
#ErrorLine INT,
#ErrorProcedure NVARCHAR(200);
-- Assign variables to error-handling functions that
-- capture information for RAISERROR.
SELECT
#OriginalErrorNumber = ERROR_NUMBER()
,#ErrorSeverity = ERROR_SEVERITY()
,#ErrorSeverity = ERROR_SEVERITY()
,#ErrorState = ERROR_STATE()
,#ErrorLine = ERROR_LINE()
,#ErrorProcedure = ISNULL(ERROR_PROCEDURE(),'-');
--Severity levels from 0 through 18 can be specified by any user.
--Severity levels from 19 through 25 can only be specified by members of the sysadmin fixed server role or users with ALTER TRACE permissions
IF #OriginalErrorNumber < 19
SET #RethrownErrorNumber = #OriginalErrorNumber
ELSE
SET #RethrownErrorNumber = 18
-- Building the message string that will contain original
-- error information.
SELECT
#ErrorMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, ' + 'Message: ' + ERROR_MESSAGE();
-- Raise an error: msg_str parameter of RAISERROR will contain
-- the original error information.
RAISERROR (#ErrorMessage,
#ErrorSeverity,
#ErrorState,
#RethrownErrorNumber, -- parameter: original error number or 18, if the original was >=19.
#ErrorSeverity, -- parameter: original error severity.
#ErrorState, -- parameter: original error state.
#ErrorProcedure, -- parameter: original error procedure name.
#ErrorLine -- parameter: original error line number.
);
Can someone explain the following line:
SELECT
#ErrorMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, ' + 'Message: ' + ERROR_MESSAGE();
I realize that the occurences of % are placeholders for a signed integers (%d) and a strinf (%s), but I don't understand which variables are mapped to these placeholders. They do not seem to map to the parameters specified in the RAISERROR call:
RAISERROR (#ErrorMessage,
#ErrorSeverity,
#ErrorState,
#RethrownErrorNumber, -- parameter: original error number or 18, if the original was >=19.
#ErrorSeverity, -- parameter: original error severity.
#ErrorState, -- parameter: original error state.
#ErrorProcedure, -- parameter: original error procedure name.
#ErrorLine -- parameter: original error line number.
);
I made two small changes to the subroutine, one to lower the severity if > 19 and the other to use the original State rather than always passing 1.
If you guys don't shoot this routine down with my minor changes down too badly, I will add logging teh error info to a user table just prior to rethrowing.
To call:
DECLARE #Zero INT
SET #Zero = 0
BEGIN TRY
SELECT 5 / #Zero
END TRY
BEGIN CATCH
PRINT 'We have an error...'
EXEC usp_RethrowError
END CATCH
Follow up questions:
1) The link above mentions that this routine would not work for deadlocks. Any reason why?
2) I added the "IF #OriginalErrorNumber < 19" part. I am not too concerned that if an error >18 occurs that the error will be rethrown will a severity of 18. In any event, I plab to abort and the original severity will be logged. Is there anything else in this routine that I need to be worried about?
Hope this will help!
You are on the right track, ErrorMessage is the pattern string that is consumed by RAISERROR. Looking at the grammar structure of RAISERROR will clear up the confusion:
RAISERROR ( { msg_id | msg_str | #local_variable }
{ ,severity ,state }
[ ,argument [ ,...n ] ] )
[ WITH option [ ,...n ] ]
The first three required arguments are the message pattern string (msg_str), severity, and state. These are followed by the optional arguments which will replace the substitution parameters in the msg_str.
So the code lets:
msg_str be ErrorMessage
severity be ErrorSeverity
state be ErrorState
arguments be RethrownErrorNumber, ErrorSeverity, ErrorState, ErrorProcedure, ErrorLine
Reference http://msdn.microsoft.com/en-us/library/ms178592.aspx