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粉8195335642023-09-13 00:11:08
I have this problem. I found that the only thing I needed to do was add
after issuing the query to get the actual entriesrecords = cursor.fetchall()
.