The rewritten title is: MySQL queries using Python
P粉604507867
P粉604507867 2023-09-12 08:59:48
0
1
533

I am new to Python and SQL. I'm trying to create a simple code to create and access a database and then create a table in an attempt to understand how SQL works. To do this I have the following code:

import mysql.connector
from companyClient import client

def createTable():
    cursor.execute("CREATE TABLE Clients" 
         "(id INT NOT NULL AUTO_INCREMENT,"
        "name VARCHAR (32) NOT NULL,"
        "surname VARCHAR (64) NOT NULL,"
        "PRIMARY KEY (id));")

    print("Table created!")


def showTable():
    print("************** Clients Table *************\n")
    tableContent = cursor.execute("SELECT * FROM Clients")
    

def createEntry():
    cursor.execute("INSERT INTO Company.Clients (name, surname) VALUES ('John','Smith')")

def addUser(userToAdd):
    try:
        cursor.execute("INSERT INTO Company.Clients VALUES %s, %s, %s", userToAdd.id, userToAdd.name, userToAdd.surname)
    except:
        print("It is not possible to add the user. Please try again.")

def findUser(userToFind):
    if(cursor.execute("SELECT * FROM Company.Clients WHERE id = %s "), userToFind.id) :
        return True
    else:
        return False

def removeUser(userToRemove):
    try:
        cursor.execute("REMOVE * FROM Company.Clients WHERE id = %s ", userToRemove.id)
    except:
        print("It is not possible to remove this user. Please try again.")

#server connection 
conexion = mysql.connector.connect(
    host="localhost",
    user="********",
    passwd="*********",
    database="Company"
)

cursor = conexion.cursor()
showTable()

I am using SQL Workbench to manage the database. I have called the createTable function to create the table "Clients" in the Company database. Using SQL Workbench, I've added an entry just to check how I can get the entry in Python. However, when I call the showTable function, the value of tableContent is empty. In addition to the current query SELECT * FROM Clients, I also tried SELECT * FROM Company.Clients and got the exact same result. How do I properly access the entries in the table?

P粉604507867
P粉604507867

reply all(1)
P粉819533564

I have this problem. I found that the only thing I needed to do was add

after issuing the query to get the actual entries
records = cursor.fetchall()

.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template