Python: MySQL DELETE issues - python

I am trying to delete a value from a table with 2 columns; twitch and name.
This is the code:
cur2 = db.cursor()
cur2.execute("SELECT twitch FROM Alan45wmzYGCc5C7TIMCdczrel.whitelist WHERE twitch NOT IN(SELECT twitch FROM Alan45wmzYGCc5C7TIMCdczrel.followers)")
result = cur2.fetchall()
db.commit()
for row in result:
unfollowers.extend(row[0])
unfollowers_join = '\n'.join(unfollowers)
print unfollowers_join
cur3 = db.cursor()
for x in follows:
cur3.execute("DELETE FROM Alan45wmzYGCc5C7TIMCdczrel.whitelist WHERE twitch = (%s);", (x,))
data_unfollower = (unfollowers_join)
db.commit()
The result is the value needing to be deleted, and the result is the cur2 query to find unmatched values.

Related

Python SQLITE3 update column value based on where condition applied to a table

I have a SQLite table that I wanted to update. This table ('abc') already has a row inserted through some other process for id and useremail. Now, I want my query to lookup this record based on where condition (on useremail) and update the value of column logintime. I am pretty new to Sqlite so need some help in figuring it out. Code below -
creating a new table (works OK)
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS abc (
id INTEGER PRIMARY KEY,
useremail TEXT,
logintime TEXT,
logouttime TEXT
);
""")
conn.commit()
conn.close()
code for inserting a record (works OK)
email = ['jojo#jojo.com']
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
c.execute('insert into abc (useremail) values(?)', email)
code for updating column logintime where value in column useremail = email:
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
now = datetime.now()
c.execute('UPDATE abc SET logintime = ? WHERE useremail = ?', (now, email))
I am having trouble with this c.execute statement.

Why I got an error when I want to count the frequency of data for multiple table in mysql? Flask is used to create web app

I want to create a dashboard widget in my web app. The first step is to count the frequency of pos, neg and neu in mysql from two table. I tried to find the solution in Flask, but not many. Hope u can help me.
The error that I got is:
MySQLdb._exceptions.OperationalError: (1241, 'Operand should contain 1 column(s)')
Table in mysql:
ques9
ques10
My code:
#app.route('/we/<string:programid>')
def we(programid):
# Create cursor
cur = mysql.connection.cursor()
result = """SELECT(
(SELECT programid,sentiment, COUNT(*)
FROM ques9 AS question9
WHERE programid= %s
GROUP BY sentiment),
(SELECT programid,q10_sentiment, COUNT(*)
FROM ques10 AS question10
WHERE programid=%s
GROUP BY q10_sentiment ))"""
data_tuple = (programid, programid)
cur.execute(result, data_tuple)
program = cur.fetchall()
mysql.connection.commit()
if result > 0:
return render_template('we.html',program=program)
else:
msg = 'No Results Found'
return render_template('we.html', msg=msg)
# Close connection
cur.close()
The group by has to be after the where clause
So i posted all the python code, i thought about adding a try, but that you can look up
Your sql has some problems like the group an his own,l but your python code has also flaws, as you can see below. The variables for sql query and the data to send, i out there so that it looks somewhat cleanber
connection = mysql.connector.connect(host='localhost',
database='test_db',
user='user',
password='password')
cur = connection.cursor(prepared=True)
sql_update_query = """SELECT(
(SELECT programid,sentiment, COUNT(*)
FROM ques9 AS question9
WHERE programid= %s
GROUP BY sentiment),
(SELECT programid,q10_sentiment, COUNT(*)
FROM ques10 AS question10
WHERE programid=%s
GROUP BY q10_sentiment ))"""
data_tuple = (programid, programid)
cur .execute(sql_update_query, data_tuple)
connection.commit()
if (connection.is_connected()):
cur.close()
connection.close()

Delete all duplicated rows except max value from python

I have a MySQL database, that I am using from my Discord python bot with AIOMySQL, but I see that by error the bot created duplicated rows with the same ID but updated the values, and that last it's what I wanted. One example of my duplicated rows:
duplicated rows
So now I want to delete all the duplicated rows, except the one with max XP.
I did a backup first, and then I was trying to save in a list all the IDs, except the ones that already are in the list. And then for every ID delete all except the max value. Like in this code:
await cur.execute("SELECT ID FROM USUARIOS;")
r = await cur.fetchall()
uslist = []
for a in r:
for b in a:
if b in uslist:
pass
elif b not in uslist:
uslist.append(b)
for user in uslist:
await cur.execute("SELECT * FROM USUARIOS WHERE ID = {} ORDER BY XP LIMIT 1;".format(user))
r = await cur.fetchone()
uid = r[0]
print(uid)
xp = r[1]
await cur.execute("DELETE FROM USUARIOS WHERE ID = {} and xp != {};".format(uid, xp))
await conn.commit()
But when I saw the DB some rows were completelely deleted, including the max values.
Assuming you want to do this in MySQL:
SELECT * FROM table WHERE XP <> (SELECT MAX(XP) FROM table) GROUP BY ID, XP, GC
UNION
SELECT * FROM table WHERE XP = (SELECT MAX(XP) FROM table)

print the most common value from sql

I have a list of words in an SQLite database and I want to get the most common value and save it in a variable.I am using python3
here is how I got my most common value.
SELECT emotion,
COUNT(emotion) AS value_occurrence
FROM chatlog
GROUP BY emotion
ORDER BY value_occurrence DESC
LIMIT 1;
May be something like this?
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('yourdb')
cur = conn.cursor()
cur.execute('''SELECT emotion,
COUNT(emotion) AS value_occurrence
FROM chatlog
GROUP BY emotion
ORDER BY value_occurrence DESC
LIMIT 1''')
rows = cur.fetchall()
    for row in rows:
        x = row[0]
y = row[1]
print(x,y)

Inserting into Postgres DB column with python

conn = psycopg2.connect("dbname=name host=host user=user password=pass port=port")
cur = conn.cursor()
with open('big shot.json') as f:
data = json.load(f)
for key in data["permissions"]:
cur.execute("INSERT INTO permissions (name) VALUES (%s);", (key,))
conn.commit()
output = cur.execute("SELECT * FROM permissions")
print(output)
I have this that I'm trying to use to create new rows in my database, but it doesn't do anything. It doesn't return any errors, but it also doesn't write to my database, and output, obviously, returns "None" in the console.
You need to fetch the data from the cursor:
cur.execute("SELECT * FROM permissions")
data = cur.fetchall()
print(data)

Categories