MySql try to get information from table - mysql

I stack on this error for a long time, I try to find some records by passing the where condition with variable. for some reason the query code that I wrote in python those not get the variable and return this error :
self._connection.handle_unread_result().
raise errors.InternalError("Unread result found").
mysql.connector.errors.InternalError: Unread result found.
and here is the code I am using to function to execute!
def unfollow_user(username, update):
if update == True:
get_list_of_not_following_back()
sql.cur.execute("SELECT user_id FROM not_following_back WHERE username = (%s) AND of_user =
(%s)",(username, current_user[0]))
unfollow_user_id = sql.cur.fetchone()
def unfollow_number_of_follower():
sql.cur.execute("SELECT username,user_id FROM not_following_back WHERE of_user =(%s)",
(current_user[0],))
list_of_user_to_unfollow = sql.cur.fetchmany(number_of_user_to_unfollow)
for each_user_to_unfollow in list_of_user_to_unfollow:
unfollow_user(each_user_to_unfollow[0], False)

I figured out the result to this problem all you need to do is defined your cur as
cur = conn.cursor(buffered=True)
I am not sure why but it work

Related

How to ignore NoneType error in tweet ID statuses_lookup

I am trying to collect tweets with tweepy from a list of tweet ids good_tweet_ids_test, using statuses_lookup.
Since the list is a bit old, some tweets will have been deleted by now. Therefore I ignore errors in the lookup_tweets function, so it does not stop each time.
Here is my code so far:
def lookup_tweets(tweet_IDs, api):
full_tweets = []
tweet_count = len(tweet_IDs)
try:
for i in range((tweet_count // 100) + 1):
# Catch the last group if it is less than 100 tweets
end_loc = min((i + 1) * 100, tweet_count)
full_tweets.extend(
api.statuses_lookup(tweet_IDs[i * 100:end_loc], tweet_mode='extended')
)
return full_tweets
except:
pass
results = lookup_tweets(good_tweet_ids_test, api)
temp = json.dumps([status._json for status in results]) #create JSON
newdf = pd.read_json(temp, orient='records')
newdf.to_json('tweepy_tweets.json')
But when I run the temp = json.dumps([status._json for status in results]) line, it gives me the error:
TypeError: 'NoneType' object is not iterable
I do not know how to fix this. I believe the type of some of the statuses is None, because they have been deleted and can therefore not be looked up now. I simply wish for my code to move on to the next status, if the type is None.
EDIT: As have been pointed out, the issue is that results is None. So now I think I need to exclude None values from the full_tweets variable. But I cannot figure out how to. Any help?
EDIT2: With further testing I have found out that results is only None when there is a tweet ID that has now been deleted in the batch. If the batch contains only active tweets, it works. So I think I need to figure out how to have my function look up the batch of tweets, and only return those that are not None. Any help on this?
Instead of implicitly returning None when there's an error, you could explicitly return an empty list. That way, the result of lookup_tweets will always be iterable, and the calling code won't have to check its result:
def lookup_tweets(tweet_IDs, api):
full_tweets = []
tweet_count = len(tweet_IDs)
try:
for i in range((tweet_count // 100) + 1):
# Catch the last group if it is less than 100 tweets
end_loc = min((i + 1) * 100, tweet_count)
full_tweets.extend(
api.statuses_lookup(tweet_IDs[i * 100:end_loc], tweet_mode='extended')
)
return full_tweets
except:
return [] # Here!

Unable to retrieve data from my sql database using pymysql

I have been trying to retrieve data from my database. I was successful, however, this time inside an if statement. The code looks like:
cur_msql = conn_mysql.cursor(cursor=pymysql.cursors.DictCursor)
select_query = """select x,y,z from table where type='sample' and code=%s"""
cur_msql.execute(select_query, code)
result2 = cur_msql.fetchone()
if(result2==None):
insert_func(code)
select_query = f"""select x,y,z from table where type='sample' and code='{code}'"""
mycur = conn_mysql.cursor(cursor=pymysql.cursors.DictCursor)
print(select_query)
mycur.execute(select_query)
result3 = mycur.fetchone()
if(result2==None):
result2=result3
Now I see that insert_func does successfully insert into the 'table'. However, on trying to fetch that row, immediately after the insertion, it returns None as if the row is absent. On debugging I find that result3 is also None. Nothing looks wrong to me but it's not working.
you donĀ“t execute it in the right way, in the cur_msql.execute, you the to send the query and a tuple of values, and you are sending just a value:
cur_msql = conn_mysql.cursor(cursor=pymysql.cursors.DictCursor)
select_query = "select learnpath_code,learnpath_id,learnpath_name from contentgrail.knowledge_vectors_test where Type='chapters' and code=%s"
cur_msql.execute(select_query, (meta['chapter_code'],))
result2 = cur_msql.fetchone()

Python MySQL No result set to fetch from

I am trying to copy the content of a table to another one, but when I execute the query i get this error:
raise errors.InterfaceError("No result set to fetch from.")
mysql.connector.errors.InterfaceError: No result set to fetch from.
I tried to modify the code in many ways, but this does not change anything, this is my code:
def query(query_string, db_connection):
while True:
try:
query_cursor = db_connection.cursor()
query_cursor.execute(query_string)
logging.info('Executing query...')
query_result = query_cursor.fetchall()
return query_result
except AttributeError:
logging.warning('%s Bad credentials' % timestamp)
And this is how i call this function:
query_to_output_db = rpgen.query("INSERT INTO auth_user.outputdb SELECT *
FROM auth_user.auth_user", connection_to_input_db)

How to use filter_by and not equals to in sqlalchemy?

I have a function defined as below to query the database table
def query_from_DB(obj, **filter):
DBSession = sessionmaker(bind=engine)
session = DBSession()
res = session.query(obj).filter_by(**filter)
session.close()
return [x for x in res]
I query the table using the request as below
query_from_DB(Router, sp_id="sp-10.1.10.149", connectivity="NO")
the above result returns the response from the DB correctly, but when I make a query using
query_from_DB(Router, sp_id!="sp-10.1.10.149", connectivity="NO")
i got an error
SyntaxError: non-keyword arg after keyword arg
What could be the possible changes I can make to get the result?
I don't believe you can use != on a keyword argument.
You can do connectivity="YES" or use the filter sqlalchemy function so you can pass == or !=, but then you won't be able to use keyword args. You'd have to pass a SQL expression like so...
res = session.query(obj).filter_by(connectivity != "NO")
This question may be helpful...
flask sqlalchemy querying a column with not equals
Did you simply try res = session.query(obj).filter_by(connectivity <> "NO") ?

MySQL-python: SELECT returns 'long' instead of the query

I'm having a problem with running a select query, using mysql-python, on an established database. The issue is that a number, what Python refers to as a long, is returned instead of the data queried- it should be noted that this number corresponds to the number of records which should be returned (I logged into the database and ran the query from MySQL to make sure).
Here is the code:
db = MySQLdb.connect(db = 'testdb', user='testuser', passwd='test', host='localhost', charset='utf8', use_unicode=True)
dbc = db.cursor()
result = dbc.execute("""SELECT %s FROM example_movie""", ('title',))
urls = [row[0] for row in result]
The last bit of code, urls = [row[0] for row in result] is to put everything into a list.
The error looks like this:
TypeError: 'long' object is not iterable
When I have python print result it returns:
('RESULT:', 52L)
When I enclose result like str(result) it just returns the number 52 (not long)
Any help and suggestions are greatly appreciated!
The return value from dbc.execute is not the results of the select; I believe it is the number of rows in the results. In order to get the actual results you need to call one of the fetch methods. See documentation here.
You should update your code to read:
db = MySQLdb.connect(db = 'testdb', user='testuser', passwd='test', host='localhost', charset='utf8', use_unicode=True)
dbc = db.cursor()
row_count = dbc.execute("""SELECT title FROM example_movie""")
results = dbc.fetchall()
urls = [row[0] for row in result]