Thats my first python sql and im trying to code this bot i got this error:
SQL CODE
import sqlite3
...
#commands.Cog.listener()
async def on_message(self, message):
db = sqlite3.connect('banco.sqlite')
cursor = db.cursor()
cursor.execute(f'SELECT nome FROM banco WHERE nome = "{message.author.id}"')
result = cursor.fetchone()
if result is None:
sql = ('INSERT INTO banco(nome, dinheiro) VALUES(?, ?)')
val = (message.author.id, 0)
cursor.execute(sql, val)
db.comit()
cursor.close()
ERROR:
File "/Users/CIP/Documents/GitHub/economia/cogs/dinheiro.py", line 54, in on_message
cursor.execute(f'SELECT column1 FROM banco WHERE column1 = "{message.author.id}"')
sqlite3.OperationalError: no such table: banco
LINE 54
cursor.execute(f'SELECT nome FROM banco WHERE nome = "{message.author.id}"')
Related
I'm writing a python code to read from mysql database:
def create_server_connection(host, user, password):
connection = None
try:
connection = pymysql.connect(host='localhost',
user='root',
password='pwd',
database='raw_data',
cursorclass=pymysql.cursors.DictCursor)
print("MySQL Database connection successful")
except err as error:
print(f"Error: '{error}'")
return connection
def read_query(connection, query):
cur = connection.cursor()
result = None
try:
cur.execute(query)
result = cur.fetchall()
return result
except err as error:
print(f"Error: '{error}'")
return cur
def get_Tables_byName(cursor, tableName):
q1 = f'''
SELECT table_name FROM raw_data.tables
where table_name like '{tableName}'; '''
res = []
cursor.execute(q1)
for row in cursor:
res.append(row[0])
return res
get_Tables_byName(cursor,'data_31942010201')
If I want to call get_Tables_byName function, what should I put in the first parameter? If I put cursor, the error message shows NameError: name 'cursor' is not defined
I would like to know why all seems to be okay but nothing is insert in my mysql database ?
I get some data from an api and I would like to insert data in table.
Using flask, python, pymysql
Thanks in advance
api = Flask(__name__)
def connect():
db = pymysql.connect(database='rtap',port=3306, host='127.0.0.1', user='root', password='',ssl_ca="{ca-cert filename}", ssl_disabled=True)
log.basicConfig(level=log.DEBUG, format='%(asctime)s %(levelname)s:\n%(message)s\n')
print("Connexion réussie")
return db
#api.route('/')
def base():
return jsonify({"version":"1.0"})
#api.route('/azure', methods=['GET'])
def read():
db = connect()
log.info('Reading Datas')
plane = "SELECT * FROM `plane`;"
cursor = db.cursor()
cursor.execute(plane)
output = cursor.fetchall()
return jsonify(output)
#api.route('/azure', methods=['POST'])
def write():
db = connect()
cursor = db.cursor()
req = request.json["response"]
# cursor.executemany("INSERT INTO `plane` (aircraft_icao, reg_number) VALUES (%s, %s);", req)
# print(req)
key = []
for i in req:
try:
if (key==[]) :
plane = "INSERT INTO `plane` (aircraft_icao, reg_number) VALUES ('{}', '{}')".format(i["aircraft_icao"], i["reg_number"])
key.append(i["reg_number"])
else:
if(i["reg_number"] not in key) : #si la key n'a pas encore été utilisée, on peut ecrire la requette, sinon on ne fait rien
plane+= ", ('{}', '{}')".format(i["aircraft_icao"], i["reg_number"])
key.append(i["reg_number"])
except Exception as e:
print("failed")
# print(plane)
cursor.execute(plane)
return jsonify(req)
if __name__=='__main__':
api.run(debug=True, port=5000, host='0.0.0.0')
traceback
Assuming that the INSERT statement looked good at that debugging print function, then you probably need to commit the material to the DB after INSERT. Try adding
db.commit()
cursor.close()
after cursor.execute().
You need to commit your table changes by doing
db.commit()
immediately after each INSERT or sequence of INSERTs. Read this.
I'm using MySQL in Python but my update function isn't updating the row and I can't understand the message error.
def atualizaCartelaTabela(campo,valor,jogador):
try:
connection = mysql.connector.connect(host='localhost',
user='root',
password='root',
database='modular')
cursor = connection.cursor()
sql = """UPDATE Cartela
SET %s = %s
WHERE PONTOS = %s"""
atualiza = (campo,valor,jogador)
cursor.execute(sql,atualiza)
except Error as e:
print("Erro ao atualizar campos da tabela Cartela ->", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
def atualizaCartelaTabela(campo,valor,jogador):
try:
connection = mysql.connector.connect(host='localhost',
user='root',
password='root',
database='modular')
cursor = connection.cursor()
sql = """UPDATE Cartela
SET %s = %s
WHERE PONTOS = %s"""
atualiza = (campo,valor,jogador)
cursor.execute(sql,atualiza)
except Error as e:
print("Erro ao atualizar campos da tabela Cartela ->", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
atualizaCartelaTabela('Um',2,'Jogador 1')
The error I'm getting:
1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Um' = 2
WHERE PONTOS = 'Jogador 1'' at line 2
And, this is the function used to create the table(working):
def criaTabelaCartela():
try:
connection = mysql.connector.connect(host='localhost',
user='root',
password='root',
database='modular')
cursor = connection.cursor()
cursor.execute("CREATE TABLE Cartela (PONTOS VARCHAR(10), Um int(2), Dois int(1), Tres int(1), Quatro int(1), Cinco int(1), Seis int(1), Full int(1), SequenciaBaixa int(1), Trinca int(1), Quadra int(1), SequenciaAlta int(1), Yahtzee int(1), PontuaçãoFinal int(1))")
connection.commit()
except Error as e:
print("Erro ao criar tabela Cartela ->", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
Looking at these 3 statements for what's causing the error:
sql = """UPDATE Cartela
SET %s = %s
WHERE PONTOS = %s"""
atualiza = (campo,valor,jogador)
cursor.execute(sql,atualiza)
When you put SET X = "y" in the update query, the column name X cannot be parameterised. Only the values.
So the column name for campo should be substituted directly in the SQL string, not during execute - but note that this is UNSAFE. Change the first parameter to the {} notation for format and leave the values as %s so that they are parameters for execute():
sql = """UPDATE Cartela
SET {} = %s
WHERE PONTOS = %s""".format(campo) # unsafe
atualiza = valor, jogador
cursor.execute(sql, atualiza)
As a safety check, make sure that the value of campo is the name of one of the columns of the table, except PONTOS or any of the import key columns. Better to check that it's in a white-list of column that you want to allow updating.
I am guessing the int - 2 is the problem here .
Try this out :
Make your SQL-query this :
sql = """
UPDATE Cartela
SET %s = CAST(%s AS int)
WHERE PONTOS = %s
"""
And where you're calling the method atualizaCartelaTabela make it this :
atualizaCartelaTabela('Um','2','Jogador 1')
Im trying convert to str
import mysql.connector
from mysql.connector import Error
def VeriEkleme(Deger1,Deger2):
try:
connection = mysql.connector.connect(host='localhost',database='pythonregister',user='pyroot',password='')
if connection.is_connected():
print("MySQL bağlantısı aktif edildi.")
mySql_insert_query = """INSERT INTO userinformations (Username, Password) VALUES """(Deger1,Deger2)
cursor = connection.cursor()
result = cursor.execute(mySql_insert_query)
connection.commit()
print("Record inserted successfully into Laptop table")
cursor.close()
except Error as e:
print("Error while connecting to MysqL", e)
def Register():
Username = input("Username:")
Password = input("Pass:")
VeriEkleme(str(Username),str(Password))
def EnterSystem():
Login = "login"
Answer = input("Login or Register?: ").lower()
if Answer == Login:
print("eşit")
Register()
else:
EnterSystem()
EnterSystem()
Login or Register?: login
eşit
Username:s
Pass:s
MySQL bağlantısı aktif edildi.
Traceback (most recent call last):
File "C:/Users/Relov/PycharmProjects/PygameProje1/PygameProjesi.py", line 36, in <module>
EnterSystem()
File "C:/Users/Relov/PycharmProjects/PygameProje1/PygameProjesi.py", line 32, in EnterSystem
Register()
File "C:/Users/Relov/PycharmProjects/PygameProje1/PygameProjesi.py", line 24, in Register
VeriEkleme(str(Username),str(Password))
File "C:/Users/Relov/PycharmProjects/PygameProje1/PygameProjesi.py", line 11, in VeriEkleme
mySql_insert_query = """INSERT INTO userinformations (Username, Password) VALUES """(Deger1,Deger2)
TypeError: 'str' object is not callable
Process finished with exit code 1
You're calling str as it is a function.
"""INSERT INTO userinformations (Username, Password) VALUES """(Deger1,Deger2)
I recommend using Prepared Statements. This is safe against SQL Injection attacks.
mySql_insert_query = """INSERT INTO userinformations (Username, Password) VALUES (%s, %s)"""
cursor = connection.cursor()
result = cursor.execute(mySql_insert_query, (Deger1, Deger2))
DELETE FROM ... doesn't work. The right parameters are passed to the function. No errors are returned.
I've tried to modify routing, passing parameters by POST and GET, and I've cried a lot in a fetal position.
conn = mysql.connect()
cursor = mysql.connect().cursor()
cursor.execute("SELECT * FROM food_on_the_table WHERE table_id = %s", table_id)
food_on_the_table = cursor.fetchall()
records = cursor.fetchall()
cursor.execute("DELETE FROM food_on_the_table WHERE row_id = %s", row_id)
conn.commit()
result = cursor.rowcount
message = "rows affected " + str(result)
cursor.close()
No row is deleted from the database. row_i is right, rows affected = 1 as expected.
Try this,
try:
conn = mysql.connect()
with conn.cursor() as cursor:
cursor.execute("SELECT * FROM food_on_the_table WHERE table_id = %s", table_id)
food_on_the_table = cursor.fetchall()
records = food_on_the_table
with conn.cursor() as cursor:
cursor.execute("DELETE FROM food_on_the_table WHERE row_id = %s", row_id)
conn.commit()
finally:
conn.close()