我是Python和SQL的新手。我正在尝试创建一个简单的代码来创建和访问一个数据库,然后创建一个表,以便试图理解SQL的工作原理。为了做到这一点,我有以下代码:
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()
我正在使用SQL Workbench来管理数据库。我已经调用了createTable函数在Company数据库中创建了表“Clients”。使用SQL Workbench,我已经添加了一个条目,只是为了检查我如何在Python中获取该条目。然而,当我调用showTable函数时,tableContent的值是空的。除了当前的查询SELECT * FROM Clients之外,我还尝试了SELECT * FROM Company.Clients,得到了完全相同的结果。我如何正确访问表中的条目?
P粉8195335642023-09-13 00:11:08
我有这个问题。我发现我需要做的唯一一件事就是在发出查询以获取实际条目之后添加
records = cursor.fetchall()
。