I'm fetching the data from the database and I would like to check the data above of the data in the same rows as the per channel to see if the cell is empty.
Here is for example table:
---------------------------
| channel | program_id
---------------------------
| ITV |
| ITV | 3021
| ITV | 3022
| ITV | 3023
Here is the code:
def update_in_database(self):
profilePath = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', 'source.db'))
conn = database.connect(profilePath)
cur = conn.cursor()
program_id = ''.join(str(x) for x in self.program_id)
cur.execute('SELECT channel, program_id FROM programs WHERE program_id=?;', (program_id,))
data = cur.fetchone()
if data:
#check if the data in a database is empty
Here is the output for the data:
(u'103 ITV', u'3021')
I have got a string of program_id which it is 3021, so I want to check the string in a database to see if the data above of the 3021 is empty so I could do something.
How I can check in a database to see if the data above of the string is empty or not?
Relational databases and SQL are not really designed to be used in this way. When using a database you should not have to fetch a given row above another row.
I would advise you to change the design of your database. This will solve your problem and will make it probably easier to work with the database.
If you can given more information on all the data that needs to be saved in the database I can help you to make a better design.
Related
I'm currently writing an rpg game in python that uses a mysql database to store info on players. However, I've come across a problem.
Sample Code of How Database has been Set Up:
playerinfo Table
userID | money | xp |
1 | 200 | 20 |
2 | 100 | 10 |
I'm trying to select the amount of money with only the value. My select query right now is
SELECT money FROM playerinfo WHERE id = 1
The full code/function for collecting selecting the info is
def get_money_stats(user_id):
global monresult
remove_characters = ["{", "}", "'"]
try:
with connection.cursor() as cursor:
monsql = "SELECT money FROM players WHERE userid = %s"
value = user_id
cursor.execute(monsql, value)
monresult = str(cursor.fetchone())
except Exception as e:
print(f"An error Occurred> {e}")
CURRENT OUTPUT:
{'money': 200}
DESIRED OUTPUT:
200
Basically, all I want to select is the INT/DATA from the player's row (identified by unique userid). How do I do that? The only solution I have is to replace the characters with something else but I don't really want to do that as it's incredibly inconvenient and messy. Is there another way to reformat/select the data?
It seems like that fetching one row gives you a dictionary of the selected columns with its values, which seems the correct approach to me. You should simply access the dictionary with the column that you want to retrieve:
monresult = cursor.fetchone()['money']
If you don't want to specify again the column (which you should) you could get the values of the dictionary as a list and retrieve the first one:
monresult = list(cursor.fetchone().values())[0]
I do not recommend the last approach because it's heavily dependent on the current status of the query and it may have to change if the query is changed.
I have created a Zapier Zap to populate data from a SmartSheet to a MySQL database. I have it branching so if the row does not already exist in MySQL a new row is created. This part works fine.
In my second branch, if the row already exists then the data in the row is updated with new data from the SmartSheet row. When existing data is replaced with new data the Zap works fine. E.g. for an example existing MySQL row:
+--------+---------------+--------------------+
| row_id | email_comment | smartsheet_orig_id |
+--------+---------------+--------------------+
| 895 | easy | 6876364645150921 |
+--------+---------------+--------------------+
In the SmartSheet if the user replaces the comment with another, the MySQL data is updated successfully, e.g:
+--------+---------------+--------------------+
| row_id | email_comment | smartsheet_orig_id |
+--------+---------------+--------------------+
| 895 | difficult | 6876364645150921 |
+--------+---------------+--------------------+
But, if the user has deleted the comment in SmartSheet and not replaced it with another, leaving the comment empty, the data is not removed from the corresponding MySQL record e.g:
+--------+---------------+--------------------+
| row_id | email_comment | smartsheet_orig_id |
+--------+---------------+--------------------+
| 895 | difficult | 6876364645150921 |
+--------+---------------+--------------------+
What I need the MySQL record to look like in this case would be:
+--------+---------------+--------------------+
| row_id | email_comment | smartsheet_orig_id |
+--------+---------------+--------------------+
| 895 | | 6876364645150921 |
+--------+---------------+--------------------+
After quite a lot of testing, and a conversation with Zapier support it appears the problem is that Null values are removed from the Zapier Code output step. So, the above case, this is a summary of what I'm expecting to happen:
Zapier Code step: email_comment = Null --> MySQL Update Row step: email_comment = Null
But at the output of the Code step my Null value for email_comment is stripped and so the MySQL Update Row Zap step interprets the record as not needing to be updated as there is no change and leaves the old value there.
I have tried, in my code, passing an empty string " " instead of a Null but I get the exact same result. The only way around I can see is to pass on some empirical character and then in the Update Row step replace that with a Null to store in the record but I can't see a way of doing that in Zapier.
I have searched Google and Here for others wrestling with this issue but have drawn a complete blank. The search strings I have been using are [Zapier] delete data, [Zapier] remove data and [Zapier] Null. None of the results of those searches seem to be dealing with the issue I am having.
This is the Python code I'm using to gather the inputs from SmartSheet:
#for a non existent input store an empty value
def gather_vals(inp):
return input_data.get(inp, emptyInput)
def pull_inputs(inputs, vinputs):
for key, value in zip(vinputs,inputs):
v = gather_vals(value)
d_inputs.update( {key:v})
x_vinputs = ['input_equipment', 'input_from', 'input_to', 'input_description', 'input_contractor', 'input_booked', 'input_confirmed', 'input_job_no', 'input_complete', 'input_est_val', 'input_inv_val', 'input_inv_no', 'input_book', 'input_update', 'input_comments_email']
x_inputs = ['equipment', 'from', 'to', 'description', 'contractor', 'booked', 'confirmed', 'job_no', 'complete', 'est_val', 'inv_val', 'inv_no', 'book', 'update', 'comments_email']
# Gather rest of inputs
emptyInput = None
d_inputs = {}
#gather pick-up/delivery date/time input data
pull_inputs(x_inputs, x_vinputs)
results.update(d_inputs)
return results
It appears that the code works, it returns no errors and when there is an updated actual value in SmartSheet it is updated in MySQL but when the comment is deleted the old value is left in MySQL.
I'm hoping someone may have a suggestion for me to follow.
This is the Zap flow:
Zapier support tells me the problem is that Nulls are being stripped off the output of the Python code step circled in red. The Nulls need to flow through to the Update Row step.
Manually entering NULL or Null or null in the Update Row step results in a string of characters being sent to MySQL. See the outpt from MySQL Workbench for that record:
Sending an empty string results in a string with quotation marks being sent to MySQL:
It appears this Zapier step will only send strings to MySQL so I guess it is a moot point that the code step strips NULLs from the output.
I am using Python to pull data from an API and update a MySQL database with those values. I realized that as my code is right now, the data I want from the API is only being INSERTED into the database the first time the code is ran but the database needs to be updated with new values whenever the code is executed after the first time. The API provides close to real - time values of position, speed, altitude etc. of current airlines in flight. My database looks like this:
table aircraft:
+-------------+------------+------------+-----------+-----------+
| longitude | latitude | velocity | altitude | heading |
+-------------+------------+------------+-----------+-----------+
| | | | | |
| | | | | |
I am quite new to MySQL and I am having trouble finding how to do this the right way. The point is to run the code in order to update the table whenever I want. Or possibly every 10 seconds or so. I am using Python's MySQLdb module in order to execute SQL commands within the python code. Here is the main part of what I currently have.
#"states" here is a list of state vectors from the api that have the data I want
states = api.get_states()
#creates a cursor object to execute SQL commands
#the parameter to this function should be an SQL command
cursor = db.cursor()
#"test" is the database name
cursor.execute("USE test")
print("Adding states from API ")
for s in states.states:
if( s.longitude is not None and s.latitude is not None):
cursor.execute("INSERT INTO aircraft(longitude, latitude) VALUES (%r, %r);", (s.longitude, s.latitude))
else:
("INSERT INTO aircraft(longitude, latitude) VALUES (NULL, NULL);")
if(s.velocity is not None):
cursor.execute("INSERT INTO aircraft(velocity) VALUES (%r);" % s.velocity)
else:
cursor.execute("INSERT INTO aircraft(velocity) VALUES (NULL);")
if(s.altitude is not None):
cursor.execute("INSERT INTO aircraft(altitude) VALUES (%r);" % s.altitude)
else:
cursor.execute("INSERT INTO aircraft(altitude) VALUES (NULL);")
if(s.heading is not None):
cursor.execute("INSERT INTO aircraft(heading) VALUES (%r);" % s.heading)
else:
cursor.execute("INSERT INTO aircraft(heading) VALUES (NULL);")
db.commit()
I am struggling to use the output of a raw query. My code is as follows:
cursor.execute("select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 order by u.teamselection1or2")
currentSelectedTeams = cursor.fetchone()
if not currentSelectedTeams:
currentSelectedTeam1 = 0
currentSelectedTeam2 = 0
else:
currentSelectedTeam1 = currentSelectedTeams[0].teamselectionid
currentSelectedTeam2 = currentSelectedTeams[1].teamselectionid
I get the following error:
currentSelectedTeam1 = currentSelectedTeams[0].teamselectionid
AttributeError: 'long' object has no attribute 'teamselectionid'
Any help would be appreciated, many thanks in advance, Alan.
PS
In case it helps the result of my query in MySQL is as follows:
mysql> select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 order by u.teamselection1or2;
+-----------------+-------------------+-----------------+---------+
| fixturematchday | teamselection1or2 | teamselectionid | user_id |
+-----------------+-------------------+-----------------+---------+
| 6 | 1 | 31 | 349 |
| 6 | 2 | 21 | 349 |
+-----------------+-------------------+-----------------+---------+
2 rows in set (0.00 sec)
Your issue is that you are using cursor.fetchone() and iterating through the result expecting it to return multiple rows.
If you want the top 2 results, you might want to use fetchmany and limit to 2 records instead.
This is what is happening under the hood:
Since you are fetching only one record, currentSelectedTeams[0] is actually returning the fixturematchday column, which it looks like is of type long and you are unable to access the attribute from it.
Another option would be to use the pretty powerful Django ORM to fetch this query result
EDIT:
If you really want to stick with cursor based implementation, try this:
cursor.execute("select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 order by u.teamselection1or2 LIMIT 2")
#Note the LIMIT 2
currentSelectedTeams = cursor.fetchall()
if not currentSelectedTeams:
currentSelectedTeam1 = 0
currentSelectedTeam2 = 0
else:
currentSelectedTeam1 = currentSelectedTeams[0].teamselectionid
currentSelectedTeam2 = currentSelectedTeams[1].teamselectionid
Note that, in an edge case scenario, where only one row is returned, this implementation would fail. (You need to check for the cursor return length, etc.. )
If this were a django queryset implementation, it would look something like this:
qs = Fixture.objects.filter(..).values("fixturematchday", "userselection__ teamselection1or2", "userselection__teamselectionid", "userselection__userid")[:2]
I have a text file and a MySQL table. the text file look like below.
new.txt
apple| 3
ball | 4
cat | 2
like this. from this text file I want to store data in the below MySQL table.
| query | count | is_prod_ready | time_of_created | last_updated |
I want to store apple,ball,cat in the column query, and all the number 3,4,2 in count column. in is_prod_ready column will be false by default, in time_of_created will take the current time. and last_updated_column will take the update time.
I have already made the table. and i am not able to store all the data into database from the text file. i have tried the below code.
import MySQLdb
con = MySQLdb.connect(host="localhost",user="root",passwd="9090547207",db="Test")
cur = con.cursor()
query = 'load data local infile "new.txt" into table data field terminated by "|" lines terminated by "\n" '
cur.execute(query)
con.commit()
con.close()
here my data base name is Test and table name is data.