Konzo
Konzo

Reputation: 29

mycursor.execute wont insert rows

I have a discord bot that will take some user input and insert it as a row into mysql. The data has been validated, but the mysql library refuses to insert it as a row. If I make it print the command instead of sending it, and then execute it from the mysql host, it inserts just fine.

async def addsourceserver(ctx, name=None, description=None, ip=None, port=None, query_port=None):
    mydb = msc(ctx.guild.id)
    mycursor = mydb.cursor(buffered=True)
    try:
        # Checking if the database has been made (theres a another command to make the db
    if name == 0 or description == 0 or ip == 0 or port == 0 or query_port == 0:
        #some more checking
    mycursor.execute("select * from source_server_info")
    existingservers = len(mycursor.fetchall()) # finds the instance number it should use when inserting (primary key kind of)
    mydb=msc(ctx.guild.id)
    mycursor = mydb.cursor(buffered=False)
    mycursor.execute(f"use `{str(ctx.guild.id)}`")
    mycursor.execute(f"""INSERT INTO source_server_info (instance, name, description, ip, port, query_port) VALUES ({existingservers+1}, '{name}', '{description}', '{ip}', {port}, {query_port})""")

It should just insert the row into mysql. What it actually does it absolutely nothing. No error is given, and nothing is changed on mysql. It's likely i'm a muppet a missing something silly, but some help would be appreciated. Thanks

Upvotes: 0

Views: 351

Answers (2)

Ferdous Hussain
Ferdous Hussain

Reputation: 73

Another way to commit is

async def addsourceserver(ctx, name=None, description=None, ip=None, port=None, query_port=None):
    mydb = msc(ctx.guild.id)
    mycursor = mydb.cursor(buffered=True)
    try:
        # Checking if the database has been made (theres a another command to make the db
    if name == 0 or description == 0 or ip == 0 or port == 0 or query_port == 0:
        #some more checking
    mycursor.execute("select * from source_server_info")
    existingservers = len(mycursor.fetchall()) # finds the instance number it should use when inserting (primary key kind of)
    mydb=msc(ctx.guild.id)
    mycursor = mydb.cursor(buffered=False)
    mycursor.execute(f"use `{str(ctx.guild.id)}`")
    mycursor.execute(f"""INSERT INTO source_server_info (instance, name, description, ip, port, query_port) VALUES ({existingservers+1}, '{name}', '{description}', '{ip}', {port}, {query_port})""")
    mycursor.commit()

Upvotes: 1

Konzo
Konzo

Reputation: 29

As it turns out, i needed to commit the changes. I did this by using autocommit=True in the connection sorry for any wasted time.

Upvotes: 0

Related Questions