MYSQL 和 python 错误 [英] MYSQL and python error

查看:41
本文介绍了MYSQL 和 python 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用python在MYSQL数据库中插入数据这是我的代码

I want to insert data in MYSQL database using python here my code

import MySQLdb
#connect to db
db= MySQLdb.connect(host= "localhost",
              user="root",
              passwd="newpassword",
              db="new_schema")
#setup cursor
cursor = db.cursor()
#create anooog1 table
cursor.execute("DROP TABLE IF EXISTS try")
sql = """CREATE TABLE try (
      COL1 INT,            COL2 INT )"""
cursor.execute(sql)


#insert to table
cursor.execute("""INSERT INTO try VALUES (%s,%s)""",(188,90))
db.commit()   
db.rollback()
#show table
cursor.execute("""SELECT * FROM try""")

print cursor.fetchall()
db.close()

但错误在我的 sql 中

but the error is in my sql

Error: `new_schema`.`try`: table data is not editable because there is no primary key defined for the table ...

我该怎么办?

推荐答案

你的错误是因为你创建了一个没有主键的表.

Your error is because you've created a table with no primary key.

使用此语句(或类似语句):

Use this statement (or similar):

sql = """CREATE TABLE try (COL1 INT, COL2 INT, PRIMARY KEY (COL1))"""

这里我们指定 COL1 是表的主键.根据需要进行修改以满足您的要求.

Here we specify that COL1 is to be the primary key for the table. Modify as you need to suit your requirements.

如果您想在表格中添加一个字符串列(长度为 128):

If you wanted to add a string column (with length 128) to your table:

 CREATE TABLE try (COL1 INT, COL2 INT, MyString VARCHAR(128), PRIMARY KEY (COL1))  

这篇关于MYSQL 和 python 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆