我是Python和SQL的新手。我正在嘗試建立一個(gè)簡單的程式碼來建立和存取一個(gè)資料庫,然後建立一個(gè)表,以便試圖理解SQL的工作原理。為了做到這一點(diǎn),我有以下程式碼:
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來管理資料庫。我已經(jīng)呼叫了createTable函數(shù)在Company資料庫中建立了表格「Clients」。使用SQL Workbench,我已經(jīng)新增了一個(gè)條目,只是為了檢查我如何在Python中取得該條目。然而,當(dāng)我呼叫showTable函數(shù)時(shí),tableContent的值是空的。除了目前的查詢SELECT * FROM Clients之外,我還嘗試了SELECT * FROM Company.Clients,得到了完全相同的結(jié)果。我如何正確存取表中的條目?
我有這個(gè)問題。我發(fā)現(xiàn)我需要做的唯一一件事就是在發(fā)出查詢以獲取實(shí)際條目之後添加
records = cursor.fetchall()
。