【问题标题】:Mysql connection with pythonmysql与python的连接
【发布时间】:2020-02-01 14:06:07
【问题描述】:

此代码运行没有错误,但没有记录添加到数据库中

mydb=sql.connect(host="localhost",user="root",passwd="")
cmd=mydb.cursor()
cmd.execute("create database if not exists library")
cmd.execute("use library")
cmd.execute("create table if not exists class_12 (roll_no int(2) not null,name varchar(30) not null,book_issued varchar(50),book_no int(6) not null)")
c=input("do u want to edd entries in the book record? y/n : ")
while c=="y":
    print("please supply the following details ")
    r=int(input("roll number of the student"))
    n=str(input("enter the name of the student"))
    bn=str(input("enter the book name"))
    BN=int(input("Enter BOOK number : "))
    inp=("insert into class_12(roll_no,name,book_issued,book_no) values(%s,%s,%s,%s)")
    val=(r,n,bn,BN)
    cmd.execute(inp,val)
    cmd.execute("commit")
    c=input("do u want to edd entries in the book record? y/n : ")```

【问题讨论】:

  • 提交 sql 查询。只有它会保存

标签: mysql python-3.x mysql-connect


【解决方案1】:

您没有将更改提交到数据库。在退出之前将提交和关闭调用添加到脚本。

mydb=sql.connect(host="localhost",user="root",passwd="")
cmd=mydb.cursor()
cmd.execute("create database if not exists library")
cmd.execute("use library")
cmd.execute("create table if not exists class_12 (roll_no int(2) not null,name varchar(30) not null,book_issued varchar(50),book_no int(6) not null)")
c=input("do u want to edd entries in the book record? y/n : ")
while c=="y":
    print("please supply the following details ")
    r=int(input("roll number of the student"))
    n=str(input("enter the name of the student"))
    bn=str(input("enter the book name"))
    BN=int(input("Enter BOOK number : "))
    inp=("insert into class_12(roll_no,name,book_issued,book_no) values(%s,%s,%s,%s)")
    val=(r,n,bn,BN)
    cmd.execute(inp,val)
    c=input("do u want to edd entries in the book record? y/n : ")
cmd.commit()
cmd.close()

【讨论】:

    【解决方案2】:

    你需要在所有插入语句之后执行cmd.commit()

    Inserting Data Using Connector/Python

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 2021-09-18
      • 2021-07-12
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多