python pymysql cursor.execute()格式化字符串报错

conn=#连接好的数据库
cursor=conn.cursor()
cursor.executr(sqls)
这个句子如果将sql语句作为sqls变量

 import pymysql
 conn=pymysql.connct(数据库配置)
 cursor=conn.cursor()
 sqls='selcet * from table where 条件=%s'%condition
 cursor.execute(sqls)
 #将字符串格式化的sql语句作为变量传入execute里面,如果上面的conditin是数字条件就不会报错,如果是字符串条件就会报错

 #如果不用字符串格式化将sql语句作为字符串直接传入execute里面,
 cursor.execute("""select * from table where condition""")
 #就不会报错  

.format我试了跟上面情况一样,也不行
这个是什么原因?求大神解答

pymysql.err.InternalError: (1054, "Unknown column '兴瀚资管' in 'where clause'")

3个回答

这个列兴瀚资管'估计编码有问题,用utf8编码一下, 为了简单,最好列名用英文,这样可以少很多问题

少个引号,%s过去的字符串不会有引号的
比如"select * from table when a=%s"%'b'就会变成:
select * from table when a=b
实际上应该是
select * from table when a='b'才对

你没有写sqls的内容具体是什么。我刚开始学sql,教程里是这样写的

sql = 'SELECT * FROM `student` ORDER BY `db_id` LIMIT %s, %s;'
cursor = conn.cursor()
cursor.execute(sql, (offset, pagesize))  # 这里用元组的形式传入参数

另外你的拼写有错误,一般IDE应该会提示语法错误的

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
请教一下python3下pymysql的execute问题

通过pymysql添加一个表名待定的表 se_name通过函数参数传入 cur.execute( "CREATE TABLE %s(a SMALLINT PRIMARY KEY),(se_name)) 报错 pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' ' ExamRes_1716'(a SMALLINT PRIMARY KEY)' at line 1") 请问如何去除%s产生的一对单引号?谢谢

ubuntu中使用Python脚本连接mysql出错:pymysql.err.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")

``` from pymysql import connect class JD(object): def __init__(self): pass def show_all_items(self): """显示所有的商品""" conn = connect(host="localhost",port=3306,user="root",password="root",database="jing_dong",charset="utf8") cursor = conn.cursor() cursor.execute("select * from goods;") for temp in cursor.fetchall(): print(temp) # 关闭Cursor对象 cursor.close() conn.close() def show_cates(self): conn = connect(host="localhost",port=3306,user="root",password="root",database="jing_dong",charset="utf8") cursor = conn.curson() cursor.execute("select name from goods_cates;") for temp in cursor.fetchall(): print(temp) # 关闭Cursor对象 cursor.close() conn.close() def run(self): while True: print("------欢迎来到京东商城------") print("1:所有的商品") print("2:所有的商品分类") print("3:所有的商品品牌分类") num = input("请输入功能对应的序号:") if num == "1": # 查询所有商品 self.show_all_items() elif num == "2": # 查询分类 self.show_cates() elif num == "3": # 查询商品分类 pass else: print("输入有错,请重新输入!") def main(): # 1.创建一个京东商城对象 jd = JD() # 2.调用这个对象的run方法,让其运行 jd.run() if __name__ == "__main__": main() ```

用executemany 可以正常插入中文,execute就会报错?

同时用用executemany 和execute 向数据库中插入一条包含中文的数据,用executemany 可以正常插入中文,execute就会报错。 报错内容为: pymysql.err.InternalError: (1054, "Unknown column '白胡子' in 'field list'") ? 用executemany写的代码: ``` add_sql = 'INSERT INTO account (id,Student_Name,grade,sex,achievement)VALUES(%s,%s,%s,%s,%s)' args = [(11,'白胡子',1,0,60)] add = cur.executemany(add_sql,args) ``` 可以正常运行,并且在数据库中可以添加一条数据。 然后是execute写的代码: ``` add_sql = 'INSERT INTO account (id,Student_Name,grade,sex,achievement)VALUES(%s,%s,%s,%s,%s)'%(12,'白胡子',1,0,59); add = cur.execute(add_sql) conn.commit() ``` 就报错了 pymysql.err.InternalError: (1054, "Unknown column '白胡子' in 'field list'") 没搞懂,哪位大佬有空告诉我哪里错误了? 网上查说是编码问题,我已经确认过 库、表是UTF-8,程序是 charset=utf8 ,没有问题的! 都是这样连接 ,用executemany就正常,execute 就报错,太奇怪了!!

关于python使用DBUtils建立连接池连接数据库报错pymysql.err.OperationalError: (2014, 'Command Out of Sync')?

我的爬虫程序使用了DBUtils建立了数据库连接池,目前在windows上运行没有问题,但在centos上运行会出现如下报错,困扰了两天了,特发此贴请教下各位大佬,感激不尽 ``` Process Process-4: Traceback (most recent call last): File "/usr/lib64/python3.6/multiprocessing/process.py", line 258, in _bootstrap self.run() File "/usr/lib64/python3.6/multiprocessing/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "/home/wwwroot/TikTokSpider/spider/main_spider.py", line 358, in run_spider user_spider(sec_uid) File "/home/wwwroot/TikTokSpider/spider/main_spider.py", line 54, in user_spider user_handler(user, db) File "/home/wwwroot/TikTokSpider/public/common.py", line 853, in user_handler db.insert(insert_user, nickname) File "/home/wwwroot/TikTokSpider/public/db_con.py", line 88, in insert return self.__edit(sql, log) File "/home/wwwroot/TikTokSpider/public/db_con.py", line 102, in __edit self.db.begin() File "/pyenvs/spider/lib64/python3.6/site-packages/DBUtils/SteadyDB.py", line 425, in begin begin(*args, **kwargs) File "/pyenvs/spider/lib64/python3.6/site-packages/pymysql/connections.py", line 410, in begin self._read_ok_packet() File "/pyenvs/spider/lib64/python3.6/site-packages/pymysql/connections.py", line 396, in _read_ok_packet raise err.OperationalError(2014, "Command Out of Sync") pymysql.err.OperationalError: (2014, 'Command Out of Sync') ```

python3是否可以获取返回操作数据库影响的行数?

环境:python3.6,IDE:pycharm,数据库:sqlserver 通过cursor.execute(mysql) 可以操作数据库,这个我知道。 现在我想插入几行数据,获取返回的影响行数,看到网上有说 直接执行语句赋个变量: effectRow = cursor.execute('insert....') Print(effectRow),就可以查到几行受影响,但是我打印出来每次都是None,明明有几行受影响,结果却是None? 请问高手,是这样获得受影响的行数吗?

Python3.5连接pymysql出现cursor问题

Ubuntu下Python3.5连接pymysql时出现错位为 with connect.cursor() as cursor: AttributeError: 'function' object has no attribute 'cursor' 以下为代码,点击错误跳到with connect.cursor() as cursor这里,不知道为什么,弄了两天了都没弄好,求大神告诉 # -*- coding:utf-8 -*- import urllib import urllib.request import re import random import pymysql.cursors #抓取所需内容 from pymysql import connect user_agent = ["Mozilla/5.0 (Windows NT 10.0; WOW64)", 'Mozilla/5.0 (Windows NT 6.3; WOW64)', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36', ] stock_total=[] #stock_total:所有页面的股票数据 stock_page:某页的股票数据 url='http://quote.stockstar.com/stock/ranklist_a_3_1_1.html' #伪装浏览器请求报头 request=urllib.request.Request(url=url,headers={"User-Agent":random.choice(user_agent)}) try: response=urllib.request.urlopen(request) except urllib.error.HTTPError as e: #异常检测 print(e.code) except urllib.error.URLError as e: print(e.reason) content=response.read().decode('gbk') #读取网页内容 #打印成功获取的页码 pattern=re.compile('<tbody[\s\S]*</tbody>') body=re.findall(pattern,str(content)) pattern=re.compile('>(.*?)<') stock_page=re.findall(pattern,body[0]) #正则匹配 stock_total.extend(stock_page) #删除空白字符 stock_last=stock_total[:] #stock_last为最终所要得到的股票数据 for data in stock_total: if data=='': stock_last.remove('') print('1') db = pymysql.Connect( host='localhost', user='root', passwd='111111', db='patest1', charset='utf8', cursorclass=pymysql.cursors.DictCursor ) try: with connect.cursor() as cursor: sql="insert into pachong values (%s, %s, %s, %s, %s)" param=[(stock_last[0]),(stock_last[1]),(stock_last[2]),(stock_last[3]),(stock_last[4]),(stock_last[5])] n=cursor.executemany(sql,param) connect.commit() finally: print('n') connect.close()

python用fetchone()可以获取数据,用fetchall()却失败了?

python小白紧急求助! 用python获取MySQL的数据,但是奇怪的是用fetchone()成功了,但是fetchall()却失败了,有没有大佬可以解答一下... ``` //fetchone() try: cursor.execute(sql) results = cursor.fetchall() for i in results: print (i+'\n') except: print("Error: unable to fecth data") ``` 结果: ![图片说明](https://img-ask.csdn.net/upload/202003/26/1585234845_341765.png) 错误情况: ``` //fetchall() try: cursor.execute(sql) results = cursor.fetchone() for i in results: print (i+'\n') except: print("Error: unable to fecth data") ``` 结果: ![图片说明](https://img-ask.csdn.net/upload/202003/26/1585235157_639570.png)

pymysql.err.ProgrammingError: (1146, "Table 'HttpCase' doesn't exist"错误无法解决

代码已经写了创建这个表,也创建成功了,但是后面查询表中的数据的时候,就会报错,显示这个表不存在

为什么Python调用Pymysql执行sql查询语句比数据库中慢得很多很多?

1、问题:简单查询数据库用户表中的用户ID,用户表比较大,有一千多万条记录,用Mysql查询select uid as 用户ID from ucenter.usr_user 即可解决,但是用Python调用Pymysql链接数据库查询的时候非常慢,等了十分钟也没解决,但是加上限制查询条数select uid as 用户ID from ucenter.usr_user limit 100很快就能得到结果,具体原因是什么呢? ``` # 打开数据库连接(ip/数据库用户名/登录密码/数据库名) db = pymysql.connect(host = "", user = "", passwd = "",\ db = "", port = ) #使用cursor()方法获取操作游标 cursor = db.cursor() sql = ''' select uid as 用户ID from ucenter.usr_user ''' #使用execute方法执行SQL语句 cursor.execute(sql) # 使用 fetchone() 方法获取一条数据 data=cursor.fetchall() # 关闭数据库连接 db.close() ```

python3.6如何返回Hive HQL语句执行结果影响的行数?

功能需求是cursor.execute(HQL)后获取Hive执行结果影响的数据行。 HQL语句类型主要为:1、INSERT INTO TABLE AS SELECT...FROM..;2、CREATE TABLE AS SELECT... FROM... 已知在Pyhon3.6+MySQL环境下,由cursor.execute(HQL)、cursor.rownumber、cursor.rowcount函数可以正确获取数据库语句的执行结果影响的行数,但在Hive上测试失败。寻求解决方案。使用过的测试伪码如下: ``` def exec_sql(cursor,SQL): try: print('cursor.execute(SQL) ==',cursor.execute(SQL)) for row in cursor: # == cursor.fetchall() print(row) print('cursor.rownumber ==',cursor.rownumber) print('cursor.rowcount ==',cursor.rowcount) except: cursor.close conn.close # 程序主体 SQL_select = 'select col,col2 from tb2_name limit 100' SQL_create = 'create table tb_name(column,colunm2) as '+ HQL_select SQL_insert = 'insert into table tb_name(colunm1,colunm2)'+ HQL_select import pymysql.cursors cursor = pymysql.Connect(host = '..',port=10010,user='..',password='..',database='..').cursor() exec_sql(cursor,SQL_select) # cursor.execute(SQL) == 100 # cursor.rownumber == 100 # cursor.rowcount == 100 exec_sql(cursor,SQL_insert) # cursor.execute(SQL) == 100 # cursor.rownumber == 100 # cursor.rowcount == 100 exec_sql(cursor,SQL_create) # cursor.execute(SQL) == 100 # cursor.rownumber == 100 # cursor.rowcount == 100 from pyhive import Hive cursor = hive.Connect(host='..', port=3306, user='..', password='..', database='..').cursor() exec_sql(cursor,SQL_select) # cursor.execute(SQL) == None # cursor.rownumber == 100 # cursor.rowcount == -1 exec_sql(cursor,SQL_insert) # cursor.execute(SQL) == None # cursor.rownumber == except # cursor.rowcount == -1 exec_sql(cursor,SQL_create) # cursor.execute(SQL) == None # cursor.rownumber == except # cursor.rowcount == -1 ```

python2.7连接数据库如何关闭cursor

cursor.close() 报错说IndentationError: Unexpected indent #encoding:utf8 import sys reload(sys) sys.setdefaultencoding('utf8') import MySQLdb try: conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root', passwd='123456',db='sjy1',charset='utf8') sql="select * from flower" cur=conn.cursor() cur.execute(sql) data=cur.fetchone() cur.close() #就这句话 conn.close() print data[2] except Exception,e: print e

python pymysql 数据库操作

我想尝试用python连接数据库,然后将表格里的数据打印出来。 数据库可以连接成功,但是在打印的时候总是出错或者出现乱码,尤其是涉及到中文 的时候。按照网上各种分享方法,还是解决不了问题。 代码如下: ![图片说明](https://img-ask.csdn.net/upload/201712/02/1512181359_371878.png) 其中 user_id, suer_pk, role_ids 是整数 和英文字符串,user_tpye 是中文。 打印结果如下: ![图片说明](https://img-ask.csdn.net/upload/201712/02/1512181909_73497.png) python 小白,求过往大神指点

Python 使用多线程写入数据库,报错

#问题描述,定义了一个函数,用于数据库写入表,直接使用函数是可以运行,但我创建了一个 多线程,在多线程里面使用运行函数,然后后错 import mysql.connector from mysql.connector import errorcode import threading,time #数据库连接参数 def sqlconn(): dbconfig={'user': 'qrcodeadmin','password': 'careyes!@#','host': '119.23.8.62','port':3308,'database': 'qrcodes','raise_on_warnings': True} try: cnx = mysql.connector.connect(**dbconfig) print('数据库连接成功') except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") else: print(err.encode) return cnx def handle(): while(True): global UID,ID for i in range(50): print(i) sqlinsert="INSERT INTO qrcode (URL,QrID) VALUES (%s,%s)",(UID,ID) cur.execute(sqlinsert[0],sqlinsert[1]) cur.execute(sqlinsert[0],sqlinsert[1]) dbcon.commit() if __name__=='__main__': global cur dbcon=sqlconn() cur=dbcon.cursor() UID=' MjAxNzEwMTExMjQyNDQ' ID='201710111242420111' #直接使用handle可以运行 handle() #------------- sql_thread=threading.Thread(target=handle) #如果使用线程就会报错 sql_thread.start() dbcon.close() print(dbcon) #报错内容 Exception in thread Thread-1: Traceback (most recent call last): File "C:\Python\lib\site-packages\mysql\connector\connection.py", line 280, in _send_cmd self._socket.send( AttributeError: 'NoneType' object has no attribute 'send' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\lib\threading.py", line 914, in _bootstrap_inner self.run() File "C:\Python\lib\threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "sqltestV0.2_Thread.py", line 34, in handle cur.execute(sqlinsert[0],sqlinsert[1]) File "C:\Python\lib\site-packages\mysql\connector\cursor.py", line 561, in exe cute self._handle_result(self._connection.cmd_query(stmt)) File "C:\Python\lib\site-packages\mysql\connector\connection.py", line 514, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "C:\Python\lib\site-packages\mysql\connector\connection.py", line 284, in _send_cmd raise errors.OperationalError("MySQL Connection not available.") mysql.connector.errors.OperationalError: MySQL Connection not available.

python提交commit()错误

![图片说明](https://img-ask.csdn.net/upload/201803/15/1521126207_767529.png) 报错 C:\Python33\python.exe C:/Users/test/sql2.py C:\Python33\lib\site-packages\pymysql\cursors.py:165: Warning: (1366, "Incorrect string value: '\\xD6\\xD0\\xB9\\xFA\\xB1\\xEA...' for column 'VARIABLE_VALUE' at row 480") result = self._query(query) Traceback (most recent call last): File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 1193, in _execute_context context) File "C:\Python33\lib\site-packages\sqlalchemy\engine\default.py", line 507, in do_execute cursor.execute(statement, parameters) File "C:\Python33\lib\site-packages\pymysql\cursors.py", line 165, in execute result = self._query(query) File "C:\Python33\lib\site-packages\pymysql\cursors.py", line 321, in _query conn.query(q) File "C:\Python33\lib\site-packages\pymysql\connections.py", line 860, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1061, in _read_query_result result.read() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1349, in read first_packet = self.connection._read_packet() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1018, in _read_packet packet.check_error() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 384, in check_error err.raise_mysql_exception(self._data) File "C:\Python33\lib\site-packages\pymysql\err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.IntegrityError: (1062, "Duplicate entry '7' for key 'PRIMARY'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:/Users/test/sql2.py", line 25, in <module> session.commit() File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 937, in commit self.transaction.commit() File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 461, in commit self._prepare_impl() File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 441, in _prepare_impl self.session.flush() File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 2237, in flush self._flush(objects) File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 2363, in _flush transaction.rollback(_capture_exception=True) File "C:\Python33\lib\site-packages\sqlalchemy\util\langhelpers.py", line 66, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File "C:\Python33\lib\site-packages\sqlalchemy\util\compat.py", line 187, in reraise raise value File "C:\Python33\lib\site-packages\sqlalchemy\orm\session.py", line 2327, in _flush flush_context.execute() File "C:\Python33\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 391, in execute rec.execute(self) File "C:\Python33\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 556, in execute uow File "C:\Python33\lib\site-packages\sqlalchemy\orm\persistence.py", line 181, in save_obj mapper, table, insert) File "C:\Python33\lib\site-packages\sqlalchemy\orm\persistence.py", line 830, in _emit_insert_statements execute(statement, multiparams) File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 948, in execute return meth(self, multiparams, params) File "C:\Python33\lib\site-packages\sqlalchemy\sql\elements.py", line 269, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 1060, in _execute_clauseelement compiled_sql, distilled_params File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 1200, in _execute_context context) File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 1413, in _handle_dbapi_exception exc_info File "C:\Python33\lib\site-packages\sqlalchemy\util\compat.py", line 203, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "C:\Python33\lib\site-packages\sqlalchemy\util\compat.py", line 186, in reraise raise value.with_traceback(tb) File "C:\Python33\lib\site-packages\sqlalchemy\engine\base.py", line 1193, in _execute_context context) File "C:\Python33\lib\site-packages\sqlalchemy\engine\default.py", line 507, in do_execute cursor.execute(statement, parameters) File "C:\Python33\lib\site-packages\pymysql\cursors.py", line 165, in execute result = self._query(query) File "C:\Python33\lib\site-packages\pymysql\cursors.py", line 321, in _query conn.query(q) File "C:\Python33\lib\site-packages\pymysql\connections.py", line 860, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1061, in _read_query_result result.read() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1349, in read first_packet = self.connection._read_packet() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 1018, in _read_packet packet.check_error() File "C:\Python33\lib\site-packages\pymysql\connections.py", line 384, in check_error err.raise_mysql_exception(self._data) File "C:\Python33\lib\site-packages\pymysql\err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1062, "Duplicate entry '7' for key 'PRIMARY'") [SQL: 'INSERT INTO user (id, name) VALUES (%(id)s, %(name)s)'] [parameters: {'id': '7', 'name': 'haha'}] (Background on this error at: http://sqlalche.me/e/gkpj) 进程已结束,退出代码1 虽然报错了,但数据库里还是插入了数据的

Python无法连接到MySQL

<div class="post-text" itemprop="text"> <p>I'm trying to connect to a database on a Linux server, everything works fine with PHP using:</p> <pre><code>$mysqli= new mysqli($_DBHOST, $_DBUSER, $_DBPASS, $_DB); </code></pre> <p>I can also connect using the command line with:</p> <pre><code>mysql -u xxx -p </code></pre> <p>But when I try to connect with Python using pymysql I get the following error:</p> <pre><code>pymysql.err.InternalError: (1130, "Host 'xxx' is not allowed to connect to this MariaDB server") </code></pre> <p>Python code:</p> <pre><code>import pymysql conn = pymysql.connect(host="xxx",user='xxx', passwd='xxx', db = 'xxx', ,port=3306, autocommit=True) </code></pre> <p>How can this even be possible? It cannot be a permission issue since PHP can connect fine, or can it?</p> </div>

用spyder库pymysql调用mysql数据库时出现的ProgrammingError: (1007, 'Unknown error 1007')如何解决?

大一学生, 今天第一次使用pymysql ``` import pymysql conn = pymysql.connect(host='localhost',user='root',passwd='*******',charset='utf8') cursor = conn.cursor() dbName='test' sql = 'show databases' cursor.execute(sql) dbs = cursor.fetchall() for db in dbs: if dbName in db: cursor.execute('drop database '+dbName) break cursor.execute('create database ' +dbName) conn.select_db(dbName) ``` 用vscode调试到这里就运行不下去了 报错 ProgrammingError: (1007, 'Unknown error 1007') 有高手能帮帮忙吗?

我的pymysql 一直报错

想请教一下大神,为什么我安装了pymysql 之后,按照网上的教程输入代码,却一直报错,原因是什么啊![图片说明](https://img-ask.csdn.net/upload/201712/06/1512553746_117231.png)

django.db.utils.InternalError: (1050, "Table 'django_content_type' already exists") 迁移文件建立数据表的时候一直报错

django.db.utils.InternalError: (1050, "Table 'django_content_type' already exists") 在网上看到很多的方法,大概都是 先删除 所有的迁移文件, 再删除 数据库中对应的 Django_migrations 表里面的所有数据 之后再进行创建迁移文件然后再执行创建数据表的操作,但是报 没有应用啥啥啥的错误。。。 接着执行: python manage.py migrate booktest --fake 结果再执行 : python manage.py migrate 还是报 1050 的错误。。。。。。。。 下面附上详细报错信息,求网友大哥们解答~~!! (django_py3) huangdonglin@huangdonglin-virtual-machine:~/django_show/test2$ python manage.py migrate Operations to perform: Synchronize unmigrated apps: messages, staticfiles Apply all migrations: admin, booktest, sessions, auth, contenttypes Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying contenttypes.0001_initial...Traceback (most recent call last): File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 124, in execute return self.cursor.execute(query, args) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query conn.query(q) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/connections.py", line 517, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/connections.py", line 732, in _read_query_result result.read() File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/connections.py", line 1075, in read first_packet = self.connection._read_packet() File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/connections.py", line 684, in _read_packet packet.check_error() File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.InternalError: (1050, "Table 'django_content_type' already exists") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 221, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in apply_migration state = migration.apply(state, schema_editor) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/migrations/migration.py", line 115, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/migrations/operations/models.py", line 59, in database_forwards schema_editor.create_model(model) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 286, in create_model self.execute(sql, params or None) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 111, in execute cursor.execute(sql, params) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/utils/six.py", line 658, in reraise raise value.with_traceback(tb) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 124, in execute return self.cursor.execute(query, args) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query conn.query(q) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/connections.py", line 517, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/connections.py", line 732, in _read_query_result result.read() File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/connections.py", line 1075, in read first_packet = self.connection._read_packet() File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/connections.py", line 684, in _read_packet packet.check_error() File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "/home/huangdonglin/.virtualenvs/django_py3/lib/python3.6/site-packages/pymysql/err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval)

执行 python manage.py makemigrations 提示错误

Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "D:\codeProgram\python3.7\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "D:\codeProgram\python3.7\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "D:\codeProgram\python3.7\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\codeProgram\python3.7\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\codeProgram\python3.7\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "D:\codeProgram\python3.7\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\codeStudy\django企业开发实战\typeidea\typeidea\blog\models.py", line 8, in <module> class Category(models.Model): File "D:\codeStudy\django企业开发实战\typeidea\typeidea\blog\models.py", line 20, in Category owner = models.ForeignKey(User, verbose_name="作者") TypeError: __init__() missing 1 required positional argument: 'on_delete' ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models class Category(models.Model): STATUS_NORMAL = 1 STATUS_DELETE = 0 STATUS_ITEMS = ( (STATUS_NORMAL, '正常'), (STATUS_DELETE, '删除'), ) name = models.CharField(max_length=50, verbose_name="名称") status = models.PositiveIntegerField( default=STATUS_NORMAL, choices=STATUS_ITEMS, verbose_name="状态") is_nav = models.BooleanField(default=False, verbose_name="是否为导航") owner = models.ForeignKey(User, verbose_name="作者") created_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间") class Meta: verbose_name = verbose_name_plural = '分类' class Tag(models.Model): STATUS_NORMAL = 1 STATUS_DELETE = 0 STATUS_ITEMS = ( (STATUS_NORMAL, '正常'), (STATUS_DELETE, '删除'), ) name = models.CharField(max_length=10, verbose_name="名称") status = models.PositiveIntegerField( default=STATUS_NORMAL, choices=STATUS_ITEMS, verbose_name="状态") owner = models.ForeignKey(User, verbose_name="作者") created_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间") class Meta: verbose_name = verbose_name_plural = '标签' class Post(models.Model): STATUS_NORMAL = 1 STATUS_DELETE = 0 STATUS_DRAFT = 2 STATUS_ITEMS = ( (STATUS_NORMAL, '正常'), (STATUS_DELETE, '删除'), (STATUS_DRAFT, '草稿'), ) title = models.CharField(max_length=255, verbose_name="标题") desc = models.CharField(max_length=1024, blank=True, verbose_name="摘要") content = models.TextField(verbose_name="正文", help_text="正文必须为MarkDown格式") status = models.PositiveIntegerField( default=STATUS_NORMAL, choices=STATUS_ITEMS, verbose_name="状态") category = models.ForeignKey(Category, verbose_name="分类") tag = models.ManyToManyField(Tag, verbose_name="标签") owner = models.ForeignKey(User, verbose_name="作者") created_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间") class Meta: verbose_name = verbose_name_plural = "文章" ```

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

Intellij IDEA 实用插件安利

1. 前言从2020 年 JVM 生态报告解读 可以看出Intellij IDEA 目前已经稳坐 Java IDE 头把交椅。而且统计得出付费用户已经超过了八成(国外统计)。IDEA 的...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

魂迁光刻,梦绕芯片,中芯国际终获ASML大型光刻机

据羊城晚报报道,近日中芯国际从荷兰进口的一台大型光刻机,顺利通过深圳出口加工区场站两道闸口进入厂区,中芯国际发表公告称该光刻机并非此前盛传的EUV光刻机,主要用于企业复工复产后的生产线扩容。 我们知道EUV主要用于7nm及以下制程的芯片制造,光刻机作为集成电路制造中最关键的设备,对芯片制作工艺有着决定性的影响,被誉为“超精密制造技术皇冠上的明珠”,根据之前中芯国际的公报,目...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

差点跪了...

最近微信又搞出了一个大利器,甚至都上了热搜,当然消息最敏捷的自媒体人,纷纷都开通了自己的视频号。01 视频号是什么呢?视频号是微信体系内的短视频,它不同...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

Vue回炉重造之router路由(更新中)

你好,我是Vam的金豆之路,可以叫我豆哥。2019年年度博客之星、技术领域博客专家。主要领域:前端开发。我的微信是 maomin9761,有什么疑问可以加我哦,自己创建了一个微信技术交流群,可以加我邀请你一起交流学习。最后自己也创建了一个微信公众号,里面的文章是我自己精挑细选的文章,主要介绍各种IT新技术。欢迎关注哦,微信搜索:臻美IT,等你来。 欢迎阅读本博文,本博文主要讲述【】,文字通...

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大胆预测下未来5年的Web开发

在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...

立即提问
相关内容推荐