重寫後的標題為:使用Python進行MySQL查詢
P粉604507867
P粉604507867 2023-09-12 08:59:48
0
1
549

我是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粉604507867
P粉604507867

全部回覆(1)
P粉819533564

我有這個問題。我發現我需要做的唯一一件事就是在發出查詢以獲取實際條目之後添加

records = cursor.fetchall()

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板