I have this mysql code that "works", but I can't print all the lines of the database, ex: the database has 5 lines, it only prints the first 2 and the others have as a result: None , what can I do ?
import mysql.connector
connect = mysql.connector.connect(host="localhost",
database="*****", user="root",
password="********")
cursor = connect.cursor()
cursor.execute("SELECT Email FROM user")
for row in cursor:
msg = cursor.fetchone()
if msg is not None:
nmsZ = [str(i) for i in msg]
msgs = str("".join(nmsZ))
print(msgs)
You shouldn't use both for row in cursor and cursor.fetchone(). The for loop is already fetching a row, then cursor.fetchone() fetches the next row. So you end up processing every other row.
So it should be either:
for msg in cursor:
msgs = "".join(map(str, msg))
print(msgs)
or
while True:
msg = cursor.fetchone()
if not msg:
break
msgs = "".join(map(str, msg))
print(msgs)
Related
I have the following code where the ph variable does not interpolates with the select query.
I am just trying to access http://localhost/testing?phone_number=1234567890 it returns like () rather particular record of the phone number.
#app.route("/testing",methods=['GET')
def testing():
ph = request.args.get('phone_number')
cur = mysql.connection.cursor()
cur.execute('''SELECT * FROM client_base where phone_number={}'''.format(ph))
results = cur.fetchall()
return ''' {} '''.format(results)
Abetter solution is using prepared statements like below
#app.route("/testing",methods=['GET')
def testing():
ph = request.args.get('phone_number')
cur = mysql.connection.cursor()
cur.execute('''SELECT * FROM client_base where phone_number=%s''',(ph,))
results = cur.fetchall()
return ''' {} '''.format(results)
I have defined a function to add rows to a MYSQL database. But it keeps giving an error saying-
_mysql_connector.MySQLInterfaceError: Column count doesn't match value count at row 1
During handling of the above exception, another exception occurred:
mysql.connector.errors.DataError: 1136 (21S01): Column count doesn't match value count at row 1
Here's my code
#add new records
def add_records():
db = msq.connect(host = "localhost", user = "root", passwd = "abhi2004", database = "Movie_Sites")
cur = db.cursor()
count = int(input("Enter number of records to enter: "))
for i in range(count):
name = input("Enter name of movie: ")
actors = input("Enter a comma separated list of actors: ")
genre = input("Enter genre: ")
ratings = float(input("Enter movie ratings: "))
sql = "insert into movies(Movie,Actors,Genre,Ratings) values ({},{},{},{})".format(name,actors,genre,ratings)
cur.execute(sql)
db.commit()
db.close()
print("Records added")
How do I fix it? What's going wrong?
I'm writing a code to generate n-grams for every record in the table by reading a specific column.
def extract_from_db(inp_cust_id):
sql_db = TatDBHelper()
t_sql = "select notes from raw_data where customer_id = {0}"
db_data = sql_db.execute_read(t_sql.format(inp_cust_id))
for row in db_data:
text = row.values()
bi_grams = generate_ngrams(text[0].encode("utf-8"), 2)
print bi_grams
def generate_ngrams(sentence, n):
sentence = sentence.lower()
sentence = re.sub(r'[^a-zA-Z0-9\s]', ' ', sentence)
tokens = [token for token in sentence.split(" ") if token != ""]
ngrams = zip(*[tokens[i:] for i in range(n)])
return [" ".join(ngram) for ngram in ngrams]
I'm getting the output like:
['i highly', 'highly recommend', 'recommend it']
['the penguin', 'penguin encounter', 'encounter was', 'was awesome']
I want the output to look like below, can anybody help me to get this.
['i highly',
'highly recommend',
'recommend it',
...
]
creat another list all_ngrams, and keep appending the values to it , using .extend(), and finally you will have all the ngrams in one list.
Try this :
def extract_from_db(inp_cust_id):
sql_db = TatDBHelper()
t_sql = "select notes from raw_data where customer_id = {0}"
db_data = sql_db.execute_read(t_sql.format(inp_cust_id))
all_ngrams = []
for row in db_data:
text = row.values()
bi_grams = generate_ngrams(text[0].encode("utf-8"), 2)
all_ngrams.extend(bi_grams)
print all_ngrams
I've a django app which fetches data from mysql db whenever a request is received.This works fine when request is processed by one user but, when more than user send request, I get a error message saying "InterfaceError at url (0, '')".
I'm using Django version 1.9.
As per my research , I included CONN_MAX_AGE in my settings.py but still I got the same error.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
**'CONN_MAX_AGE': None**
}
}
my models.py
connection = pymysql.connect(host='localhost',user='user',password='password',db='db_name',port=3306,charset='utf8',cursorclass=pymysql.cursors.DictCursor)
def execute(query):
cur = connection.cursor()
cur.execute(query)
data = cur.fetchall()
connection.commit()
cur.close()
return data
def trending_assets():
sql = "select * from media_recommendation_engine.content_table t1 inner join (SELECT movieId,rank from" \
" media_recommendation_engine.asset_ranks limit 10) t2 on t1.movieId = " \
"t2.movieId order by t2.rank asc ;;"
data = execute(sql)
return data
views.py
#permission_classes((permissions.IsAuthenticated,))
class Trending(viewsets.GenericViewSet):
def list(self,request):
if request.query_params['type']=='trending':
result_data = models.trending_assets()
return Response(models.formatter(result_data))
#
else:
return JsonResponse({'message': 'Wrong Argument pass'},status= 400)
You should connect the db each time you need to when a request need to be processed. Earlier I used a connection globally. And do not use db.close().
def execute(query):
connection = pymysql.connect(host='localhost', user='user', password='passsword', db='db_name', port=3306, charset='utf8', cursorclass=pymysql.cursors.DictCursor)
cur = connection.cursor()
cur.execute(query)
data = cur.fetchall()
connection.commit()
cur.close()
return data
def trending_assets():
sql = "select * from media_recommendation_engine.content_table t1 inner join (SELECT movieId,rank from" \
" media_recommendation_engine.asset_ranks limit 10) t2 on t1.movieId = " \
"t2.movieId order by t2.rank asc ;;"
data = execute(sql)
return data
I'm struggling with the formatting on a mysql query and I was hoping you could point me in the right direction. Here are the queries
sql = "SELECT price FROM inventory WHERE card_name = %s AND card_set = %s"
sql_rare = "SELECT rarity FROM inventory WHERE card_name = %s AND card_set = %s"
sql_count = "SELECT count(*) FROM inventory WHERE card_name = %s AND card_set = %s
When I run the following code, utilizing the sql_count query, i get an error saying:
File "C:\Users\Spencer\Desktop\Python Programs\PythonMTG\Revision3AutoAndManual\51515\magicassistantcsv.py", line 264, in output_card
for row in getmtgprice.query(sql_count, ([card_name, set_name])):
TypeError: query() takes exactly 4 arguments (3 given)
Here is the code producing this error:
getmtgprice = PriceCheck()
for row in getmtgprice.query(sql_count, ([card_name, set_name])):
if row[0] ==0:
priced_card = '0.00'
And here is the PriceCheck function:
class PriceCheck(object):
def __init__(self):
self.conn = MySQLdb.connect(host='localhost', user='root', passwd='', db='mscan')
self.c = self.conn.cursor()
def query(self, arg, cardname, setname):
self.c.execute(arg, cardname, setname)
return self.c
def __del__(self):
self.conn.close()
Do you see where I went wrong?
Your query method takes separate arguments for cardname and setname, not a list containing both. So, instead of:
for row in getmtgprice.query(sql_count, ([card_name, set_name])):
You should have:
for row in getmtgprice.query(sql_count, card_name, set_name):