Having trouble getting MySQL data returned - mysql

I have a long Perl script that in other places returns MySQL table data successfully using binds:
$query2 = "SELECT tblExportFiles.CompID, CompEmail, export_id, export_name, query, num_records, sample_rate, record_startnum, Description, Pull_Type, remote_CompID FROM tblExportFiles INNER JOIN tblCustomers USING(CompID) WHERE done=0 ORDER BY export_id ASC ;";
$sqlQuery2 = $dbh->prepare( $query2 );
$sqlQuery2->execute or die "can't execute the query: " . $sqlQuery2->errstr;
$sqlQuery2->bind_columns(
\$CompID, \$CompEmail, \$export_id, \$fileName,
\$queryFile, \$numRecords, \$sampleRate, \$recStartNum,
\$description, \$qType, \$remote_CompID
);
while ( $sqlQuery2->fetch ) { ... }
But when I do the same sort of query here, it fails to return any values but doesn't throw an error:
my $ftpQuerySQL = "SELECT tblResellersData.http_address ,ftp_address, ftp_username, ftp_password, ftp_dir, http_name, tblResellerCustomers.CompEmail FROM tblResellersData, tblResellerCustomers WHERE tblResellerCustomers.User_ID = '$remote_CompID' AND tblResellersData.CompID = '$CompID' ; ";
print "FTP SQL = $ftpQuerySQL\n\n";
$QueryFTP = $dbh->prepare( $ftpQuerySQL );
$QueryFTP->execute() or die "can't execute the query: " . $QueryFTP->errstr;
$QueryFTP->bind_columns(
\$http_address, \$ftp_address, \$ftp_username, \$ftp_password,
\$ftp_dir, \$remote_name, \$CompEmail
);
$QueryFTP->fetch();
It throws warnings
Use of uninitialized value $ftp_address in concatenation (.) or string at ./Cron_file_output.pl line 302.
Use of uninitialized value $ftp_dir in concatenation (.) or string at ./Cron_file_output.pl line 302.
Use of uninitialized value $ftp_username in concatenation (.) or string at ./Cron_file_output.pl line 302.
is a located in
Use of uninitialized value $ftp_dir in scalar chomp at ./Cron_file_output.pl line 303.
Use of uninitialized value $http_address in concatenation (.) or string at ./Cron_file_output.pl line 304.
Use of uninitialized value $ftp_address in concatenation (.) or string at ./Cron_file_output.pl line 304.
Use of uninitialized value $ftp_username in concatenation (.) or string at ./Cron_file_output.pl line 304.
Use of uninitialized value $ftp_password in concatenation (.) or string at ./Cron_file_output.pl line 304.
Use of uninitialized value $ftp_dir in concatenation (.) or string at ./Cron_file_output.pl line 304.
Use of uninitialized value $remote_name in concatenation (.) or string at ./Cron_file_output.pl line 304.
RETURNED VALUES......., , , , , , j#adki87.com
Use of uninitialized value $ftp_address in concatenation (.) or string at ./Cron_file_output.pl line 310.
But when I ran the same SQL under phpMyAdmin, it gave this result:
http_address website's url ftp_address ftp_username ftp_password ftp_dir http_name
http://www.highpeaksbyway.com/ highpeaksbyway.com data#highpeaksbyway.com dataUUU666##) pulls/ TEST ME

What are lines 302, 304, and 310?
It looks like your criteria (the WHERE conditions) are failing, and the statement returns no records
What does $QueryFTP->fetch return? You need to check its status before you use it. That is the major difference between the code that you think "works" and your problem case
You need to check the values of $CompID and $remote_CompID before the execute. You should also use placeholders in the prepare call, and supply the values in execute

Related

Command raised an exception: OperationalError: near "<": syntax error sqlite3 discord.py

cursor.execute(f"UPDATE blackasjackas SET pirmas_korta = {pirmas_korta} WHERE userid={ctx.author.id}")
I'm having a problem with this line, it's giving me the operationalerror near "<" and I can't seem to figure out how to fix it
pirmas_korta returns a string "<:2H:804013503354634280>"
I'm not a python specialist, but SQL-standart requires strings to be apostrophed, so since pirmas_korta is some kind of a string value, update statement should look like the following
f"UPDATE blackasjackas SET pirmas_korta = '{pirmas_korta}' WHERE userid={ctx.author.id}"

python error on string format with "\n" exec(compile(contents+"\n", file, 'exec'), glob, loc)

i try to construct JSON with string that contains "\n" in it like this :
ver_str= 'Package ID: version_1234\nBuild\nnumber: 154\nBuilt\n'
proj_ver_str = 'Version_123'
comb = '{"r_content": {0}, "s_version": {1}}'.format(ver_str,proj_ver_str)
json_content = json.loads()
d =json.dumps(json_content )
getting this error:
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Dev/python/new_tester/simple_main.py", line 18, in <module>
comb = '{"r_content": {0}, "s_version": {1}}'.format(ver_str,proj_ver_str)
KeyError: '"r_content"'
The error arises not because of newlines in your values, but because of { and } characters in your format string other than the placeholders {0} and {1}. If you want to have an actual { or a } character in your string, double them.
Try replacing the line
comb = '{"r_content": {0}, "s_version": {1}}'.format(ver_str,proj_ver_str)
with
comb = '{{"r_content": {0}, "s_version": {1}}}'.format(ver_str,proj_ver_str)
However, this will give you a different error on the next line, loads() missing 1 required positional argument: 's'. This is because you presumably forgot to pass comb to json.loads().
Replacing json.loads() with json.loads(comb) gives you another error: json.decoder.JSONDecodeError: Expecting value: line 1 column 15 (char 14). This tells you that you've given json.loads malformed JSON to parse. If you print out the value of comb, you see the following:
{"r_content": Package ID: version_1234
Build
number: 154
Built
, "s_version": Version_123}
This isn't valid JSON, because the string values aren't surrounded by quotes. So a JSON parsing error is to be expected.
At this point, let's take a look at what your code is doing and what you seem to want it to do. It seems you want to construct a JSON string from your data, but your code puts together a JSON string from your data, parses it to a dict and then formats it back as a JSON string.
If you want to create a JSON string from your data, it's far simpler to create a dict with your values and use json.dumps on that:
d = json.dumps({"r_content": ver_str, "s_version": proj_ver_str})

Mysql error Invalid parameter number: parameter was not defined

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"

Querying cassandra error no viable alternative at input 'ALLOW'

I'm trying to run a query on Cassandra through spark.
When running this command:
val test = sc.cassandraTable[Person](keyspace,table)
.where("name=?","Jane").collect
I get the appropriate output for the query.
When I try to use the where statement to enter the query as a whole string I get an error.
I receive the query as a json:
{"clause": " name = 'Jane' "}
then turn it into a string.
When running
val query = (json \ "clause").get.as[String]
//turns json value into a string
val test = sc.cassandraTable[Person](keyspace,table)
.where(query).collect
I get the following error:
java.io.IOException: Exception during preparation of SELECT "uuid", "person", "age" FROM "test"."users" WHERE token("uuid") > ? AND token("uuid") <= ? AND name = Jane ALLOW FILTERING: line 1:232 no viable alternative at input 'ALLOW' (...<= ? AND name = [Jane] ALLOW...)
at com.datastax.spark.connector.rdd.CassandraTableScanRDD.createStatement(CassandraTableScanRDD.scala:288)
at com.datastax.spark.connector.rdd.CassandraTableScanRDD.com$datastax$spark$connector$rdd$CassandraTableScanRDD$$fetchTokenRange(CassandraTableScanRDD.scala:302)
at com.datastax.spark.connector.rdd.CassandraTableScanRDD$$anonfun$18.apply(CassandraTableScanRDD.scala:328)
at com.datastax.spark.connector.rdd.CassandraTableScanRDD$$anonfun$18.apply(CassandraTableScanRDD.scala:328)
at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434)
at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440)
at com.datastax.spark.connector.util.CountingIterator.hasNext(CountingIterator.scala:12)
at scala.collection.Iterator$class.foreach(Iterator.scala:893)
at com.datastax.spark.connector.util.CountingIterator.foreach(CountingIterator.scala:4)
at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59)
I suspect that when I turn the json value " name = 'Jane' " into a string, I lose the single quotes hence I get " name = Jane " which of course raises an error. I tried escaping the single quotes with \ and with a second pair of single quotes around the name Jane {"clause": " name = ''Jane'' "}. It doesn't solve the issue.
Edit: After further testing it's definitely the json that loses the single quotes and CQL needs them to perform the query. Can anyone suggest a way to escape/save the presence of the single quotes? I tried escaping with \ double single quotes '' . Is there a way to use JSON to provide proper whole CQL statements?
Please use Unicode character \u0027.

Storing a String saved as a Variable in a MySQL database?

In a ruby script that sends information to the TWILIO API, I have a string of characters of characters that their (Twilio's) API outputs. I then have the console output it so I can save it as a variable and reuse it later:
#client = Twilio::REST:Client.new account_sid, auth_token
call = #client.account.calls.create({:from => 'incoming', :to => 'outgoing', :url => 'url', :method => 'GET'})
puts call.sid
This part is functional, but now when I rename the variable (// #incoming_Cid=call.sid //) as to input it into a MySQL database, I bump into an issue. (The 34 character ID has numbers and letters, so I define the datatype as VARCHAR).
begin
dbh = DBI.connect("DBI:Mysql:db_name:localhost",
"user", "pass")
dbh.do ("INSERT INTO calls (column_name)" #//Select the column to insert
"VALUES (incoming_Cid)") #Insert the 34 character string.
dbh.commit
puts "Customer SID has been recorded"
rescue
puts "A database occurred"
puts "Error code: #{e.err}"
puts "Error message: #{e.errstr}"
ensure
dbh.disconnect if dbh
end
Right here at the dbh.do ("INSERT INTO calls " line if I put the incoming_Cid variable in the VALUES() instead of seeing a 34-char-string, like CA9321a83241035b4c3d3e7a4f7aa6970d, I literally see 'incoming_Cid' appear in the database when I execute select * in calls.
How can I resolve this issue?
You need to use string interpolation: "VALUES (#{#incoming_Cid})"