Following SQL statement is creating an error with message :
"Message: Fatal error encountered during command execution."
"Inner exception: Parameter '#LastUserID' must be defined."
If I directly use LAST_INSERT_ID() instead of LastUserID, it always returns zero (hence fails at second insert) when executed like this.
I don't see my syntax is different than in mySQL document.
Could some one help me ?
string Query = #"INSERT INTO login (" +
"LOGIN_EMAIL," +
"LOGIN_PASSWORD," +
"LOGIN_SALT," +
"LOGIN_LAST_LOGIN_DATE," +
// "LOGIN_LAST_LOGIN_LOCATION," +
"LOGIN_ACCOUNT_STATUS," +
"LOGIN_LOGIN_ATTEMPTS," +
"LOGIN_CREATED_DATE) " +
"VALUES (" +
"#Parameter2," +
"#Parameter3," +
"#Parameter4," +
"#Parameter5," +
// "#Parameter6," +
"#Parameter6," +
"#Parameter7," +
"#Parameter8); " +
"SET #LastUserID = LAST_INSERT_ID(); " +
"INSERT INTO user_role (" +
"USER_ROLE_USER_ID," +
"USER_ROLE_ROLE," +
"USER_ROLE_STATUS," +
"USER_ROLE_CREATED_DATE) " +
"SELECT " +
"#LastUserID," +
"#Parameter9," +
"#Parameter10," +
"#Parameter11 " +
"FROM dual WHERE NOT EXISTS (SELECT USER_ROLE_USER_ID FROM user_role " +
"WHERE USER_ROLE_USER_ID = #LastUserID AND USER_ROLE_ROLE = #Parameter9)";
MySqlCommand oCommand = new MySqlCommand(Query, oMySQLConnecion);
oCommand.Transaction = tr;
Create a procedure in which you first do your insert, cache the last inserted id, do the other insert and let it print out your parameters with a bool if your last insert worked or not. That way you can debug it properly.
In general you should avoid concatinating strings to generate sql-commands or you might get troubles with parameters containing unexpected characters or be hit by a injection.
Simple fix : Replace "$LastUserID" with "$'LastUserID'". The ephostophy makes the difference.
Related
I am using Tradingview Pinescript 4.0.
This message was made with reference to :
https://stackoverflow.com/questions/66926863/combining-data-from-different-tradingview-4-0-indicators-for-the-purpose-of-crea
Basically, what I would like to do is use Tradingview 4.0 Pinescript Strategies with the Tradingview Webhook Alert system.
The closest I have seen that provides a hint a to how one can do this is found in this particular video (for a different product):
https://support.mudrex.com/hc/en-us/articles/360050211072-Automating-an-alert-from-a-Strategy-on-TradingView
It would use something like the "comment" below:
// strategy.entry(id=tostring(randomNumber), long=false,
comment="{"id" : " + tostring(randomNumber) + ", "action" :
"reverse_short_to_long"}")
I need to send JSON from the Strategy as part of the Web alert. According to the video, one would use something like:
{{ strategy.comment }}
Are there any solid examples as to how this could be done?
Tradingview sends the alert as JSON if the string is formatted as JSON. I suggest using the alert() function instead of alertcondition. It's then easy to construct a string in a JSON format however you want. Here's a nasty function I use to generate alerts.
customalert(_name, _symbol, _type, _asset_type, _action, _risk_value, _risk_percent, _sl, _tp1,_tp1_percent, _tp2, _tp2_percent, _message) =>
alert_array = array.new_string()
if _name != ''
array.push(alert_array, '"Name": "' + _name + '"')
if _symbol != ''
array.push(alert_array, '"Symbol": "' + _symbol + '"')
if _type != ''
array.push(alert_array, '"Type": "' + _type + '"')
if _asset_type != ''
array.push(alert_array, '"Asset Type": "' + _asset_type + '"')
if _action != ''
array.push(alert_array, '"Action": "' + _action + '"')
if _risk_value != 0
array.push(alert_array, '"Risk Value": "' + tostring(_risk_value) + '"')
if _risk_percent != 0
array.push(alert_array, '"Risk Percentage": "' + tostring(_risk_percent) + '"')
if _tp1 != 0
array.push(alert_array, '"Take Profit 1 Level": "' + tostring(_tp1) + '"')
if _tp1_percent != 0
array.push(alert_array, '"Take Profit 1 Percent": "' + tostring(_tp1_percent) + '"')
if _tp2 != 0
array.push(alert_array, '"Take Profit 2 Level": "' + tostring(_tp2) + '"')
if _tp2_percent != 0
array.push(alert_array, '"Take Profit 2 Percent": "' + tostring(_tp2_percent) + '"')
if _sl != 0
array.push(alert_array, '"Stop Loss Level": "' + tostring(_sl) + '"')
if _message != ''
array.push(alert_array, '"Message": "' + _message + '"')
alertstring = '{' + array.join(alert_array,', ') + '}'
alert(alertstring, alert.freq_once_per_bar_close)
You don't need to do anything complex though, the most important line is the alertstring = '{' + array.join(alert_array,', ') + '}'
You just need to make sure the string starts and ends with curly braces and is properly formatted JSON.
Could just as easily:
alert('{"Symbol": "' + syminfo.ticker + '", "Action": "Entry"}', alert.freq_once_per_bar_close)
You just need to be careful with your double and single quotes.
Also, this is explained if you go to set up an alert and click the option to learn more about alerts, at least the fact that formatting as JSON is what determines whether the alert is sent as text or JSON. As for the {{}}s, those are used to send a limited set of values for use with the alertcondition() function, and I don't really see an advantage to using them vs tostring() with alert().
Another thing to keep in mind is that this necessitates sending your data as strings, so you will need to make sure to convert back to ints and floats as necessary on the server side.
I'm trying to insert JSON data into an MySQL database:
def mapClients():
for d in devices:
clientMap = d['dot11.device']['dot11.device.associated_client_map'].keys()
for item in clientMap:
clientList = kr.device_by_mac(item)
times = kr.device_summary_since()
for c in clientList:
sqlMac = c['kismet.device.base.macaddr'],
sqlType = c['kismet.device.base.type'],
sqlManuf = c['kismet.device.base.manuf'],
ktime = c['kismet.device.base.last_time'],
for t in ktime:
sqlTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))
cur.execute("INSERT INTO devices(apID,mac,type,manuf,last_seen) VALUES(1,'" + str(sqlMac) + "','" + str(sqlType) + "','" + str(sqlManuf) + "','" + sqlTime + "');")
conn.commit()
mapClients()
This returns the following error:
pymysql.err.ProgrammingError: (1064, u"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 'VALUES(1,'(u'58:E2:8F:CF:20:B3',)','(u'Wi-Fi Client',)','(u'Apple',)','20-10-201' at line 1")
I can see from the error that the various values are being suffixed with a 'u'. I understand through a lot of searching and learning that (I think) this means the data is unicode.
What I want to do is find a way of converting/decoding the data so the INSERT statements work. Some of the variables are tuples, some strings. Any help much appreciated.
You are inserting tuples, not strings; remove the trailing commas:
sqlMac = c['kismet.device.base.macaddr']
sqlType = c['kismet.device.base.type']
sqlManuf = c['kismet.device.base.manuf']
ktime = c['kismet.device.base.last_time']
sqlTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ktime))
It’s the trailing comma that turns those expressions into tuples, and str() on a tuple gives you the container Unicode string as the u'....' representation that then clashes with the ' quoting you are adding.
Note that removes the need to loop over ktime!
Next, you really want to use SQL parameters, not string concatenation. Use placeholders instead of '" + str(...) + "', and leave handling of quoting to the database adapter:
cur.execute("""
INSERT INTO devices (apID, mac, type, manuf, last_seen)
VALUES (1, %s, %s, %s, %s)
""", (sqlMac, sqlType, sqlManuf, sqlTime))
The %s are the placeholders; depending on your exact MySQL Python library, you may need to use ? questionmarks instead.
Not only would this let you avoid having to think about quoting, it also removes a serious security issue: the JSON you load could contain a SQL injection attack and SQL parameters are the best way to neutralise that attack vector.
For the error message you posted, you have forgotten to place the closing parentheses before the VALUES in your SQL Query. The query should be like:
cur.execute("INSERT INTO devices(apID,mac,type,manuf,last_seen) VALUES(1,'" + str(sqlMac) + "','" + str(sqlType) + "','" + str(sqlManuf) + "','" + str(sqlTime) + "');")
I'm trying to use Groovy withBatch function and it's really slow (15 sec). I've tried with different batch sizes (10, 400 ...) and it always take a lot of time doing each batch.
It's the second query that I write with it and there are both slow.
Here's my code. Is there a bug in it or am I using it the wrong way ?
static updateCSProducts(def conn, def webProductRows){
conn.withBatch(400, """
UPDATE cscart_products p
SET usergroup_ids=:usergroup_ids,
b2b_group_ids=:b2b_group_ids,
b2b_desc_hide=:b2b_desc_hide
WHERE product_code = :product_code
OR product_id = (SELECT product_id FROM cscart_product_options_inventory WHERE product_code = :product_code)
""") { ps ->
webProductRows.each({row ->
ProductType type = ProductType.fromCode(row.type)
String userGroupIds = type.getProductAvailabilityUserGroup().collect{it.getId()}.join(",")
String b2bGroupIds = type.getB2bUserGroup().collect{it.getId()}.join(",")
boolean b2bDescHide = !type.getB2bUserGroup().isEmpty()
println row.id + " " + userGroupIds + " " + b2bGroupIds + " " + b2bDescHide
ps.addBatch(product_code:row.id, usergroup_ids:userGroupIds, b2b_group_ids:b2bGroupIds, b2b_desc_hide:b2bDescHide)
})
}
}
I'm using MySql as Database. When I'm looking at SQL connections, I don't really see any connection running a query while I'm waiting for the next batch.
EDIT:
I've removed the queries and it still very slow.
Heres the updated version:
conn.withBatch(400, """
UPDATE cscart_products p
SET usergroup_ids=:usergroup_ids,
b2b_group_ids=:b2b_group_ids,
b2b_desc_hide=:b2b_desc_hide
WHERE p.product_code = :product_code
""") { ps ->
webProductRows.each({row ->
ProductType type = ProductType.fromCode(row.type)
String userGroupIds = type.getProductAvailabilityUserGroup().collect{it.getId()}.join(",")
String b2bGroupIds = type.getB2bUserGroup().collect{it.getId()}.join(",")
String b2bDescHide = !type.getB2bUserGroup().isEmpty() ? 'Y' : 'N'
println row.id + " " + userGroupIds + " " + b2bGroupIds + " " + b2bDescHide
ps.addBatch(product_code:row.id, usergroup_ids:userGroupIds, b2b_group_ids:b2bGroupIds, b2b_desc_hide:b2bDescHide)
})
}
You're running tons of queries on each and every update. You'd be better off retrieving a list of data and then looping over that. It's not withBatch that's the bottleneck, it's your implementation.
I am having a field with string values as "First Middle Last" and i want to show the initial characters from this string as "FML"
how can i do it in terms of ssrs expression ?
Assuming the field MyString always has 3 words the following will find the first character of the First, Second and Last words. This admittedly doesn't handle instances where there are more or less than 3 words, but hopefully should get you started if you require more finesse.
=Left(Fields!MyString.Value, 1) + " " +
Left(Mid(Fields!MyString.Value, InStr(Fields!MyString.Value, " ") + 1), 1) + " " +
Left(Mid(Fields!MyString.Value, InStrRev(Fields!MyString.Value, " ") + 1), 1)
Edit
To cope with the possiblity of only two words (as suggested in the commetns below) a check for the index of the spaces could be used to ensure that they are not the same, and thus 3 words exist. This would make the code as follows
=Left(Fields!MyString.Value, 1) + " " +
Left(Mid(Fields!MyString.Value, InStr(Fields!MyString.Value, " ") + 1), 1) +
iif(InStrRev(Fields!MyString.Value, " ") > InStr(Fields!MyString.Value, " "),
" " + Left(Mid(Fields!MyString.Value, InStrRev(Fields!MyString.Value, " ") + 1), 1),
"")
Does anyone know what could be causing this error? I'm trying to convert a MySQL site to Postgres so I can host on Heroku. I'm new to database syntax, and this problem has been bugging me for days.
PG::Error: ERROR: syntax error at or near "ON"
LINE 1: ...tores ("key", "value") VALUES ('traffic:hits', 0) ON DUPLICA...
^
Here's the github page for the site I'm trying to convert. https://github.com/jcs/lobsters
This is the query. I added the backslash double quotes in replace of `.
if Rails.env == "test"
Keystore.connection.execute("INSERT OR IGNORE INTO " <<
"#{Keystore.table_name} (\"key\", \"value\") VALUES " <<
"(#{q(key)}, 0)")
Keystore.connection.execute("UPDATE #{Keystore.table_name} " <<
"SET \"value\" = \"value\" + #{q(amount)} WHERE \"key\" = #{q(key)}")
else
Keystore.connection.execute("INSERT INTO #{Keystore.table_name} (" +
"\"key\", \"value\") VALUES (#{q(key)}, #{q(amount)}) ON DUPLICATE KEY " +
"UPDATE \"value\" = \"value\" + #{q(amount)}")
end
Postgres' INSERT doesn't support MySQL's variant INSERT ... ON DUPLICATE KEY UPDATE.
For alternatives see the answers to this question.
I was working on this exact code last night, here's an initial take at how I fixed it, following this answer :
def self.put(key, value)
key_column = Keystore.connection.quote_column_name("key")
value_column = Keystore.connection.quote_column_name("value")
if Keystore.connection.adapter_name == "SQLite"
Keystore.connection.execute("INSERT OR REPLACE INTO " <<
"#{Keystore.table_name} (#{key_column}, #{value_column}) VALUES " <<
"(#{q(key)}, #{q(value)})")
elsif Keystore.connection.adapter_name == "PostgreSQL"
Keystore.connection.execute("UPDATE #{Keystore.table_name} " +
"SET #{value_column} =#{q(value)} WHERE #{key_column} =#{q(key)}")
Keystore.connection.execute("INSERT INTO #{Keystore.table_name} (#{key_column}, #{value_column}) " +
"SELECT #{q(key)}, #{q(value)} " +
"WHERE NOT EXISTS (SELECT 1 FROM #{Keystore.table_name} WHERE #{key_column} = #{q(key)}) "
)
elsif Keystore.connection.adapter_name == "MySQL" || Keystore.connection.adapter_name == "Mysql2"
Keystore.connection.execute("INSERT INTO #{Keystore.table_name} (" +
"#{key_column}, #{value_column}) VALUES (#{q(key)}, #{q(value)}) ON DUPLICATE KEY " +
"UPDATE #{value_column} = #{q(value)}")
else
raise "Error: keystore requires db-specific put method."
end
true
end
There's a number of things to be fixed in the lobsters codebase beyond just this for postgres compatability - found mysql specific things in other controller files. I'm currently working on them at my own lobsters fork at https://github.com/seltzered/journaltalk - postgres fixes should be commited on there in the coming day or two.