重写后的标题为:使用Python进行MySQL查询
P粉604507867
P粉604507867 2023-09-12 08:59:48
0
1
548

我是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()

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板