我对这个 django raw sql 请求感到很困惑
设置.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'myapp', # Or path to database file if using sqlite3.
'USER': 'postgres', # Not used with sqlite3.
'PASSWORD': 'password', # Not used with sqlite3.
'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '5432', # Set to empty string for default. Not used with sqlite3.
#'OPTIONS': { 'init_command': 'SET storage_engine=INNODB;' }
},
'mysql': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'myapp', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'password', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
#'OPTIONS': { 'init_command': 'SET storage_engine=INNODB;' }
}
}
sql请求
from django.db import connections
cursor = connections['mysql'].cursor()
cursor2 = connections['default'].cursor()
cursor.execute("select user_id,group_id from auth_user_groups")
cursor2.execute("select id,username from auth_user")
for r in cursor2.fetchall():
self.stdout.write(r[0])
cursor2.execute("insert into auth_user_groups(user_id,group_id) values (1,1);")
它返回一个错误(我在 auth_user 表中有数百个用户)
AttributeError: 'int' object has no attribute 'endswith'
排队
for r in cursor2.fetchall():
self.stdout.write(r[0])
我期待这条线
cursor2.execute("insert into auth_user_groups(user_id,group_id) values (1,1);")
将一行插入 auth_user_groups 表位,但它没有。
这里发生了什么?
谢谢
更新
现在问题已经解决了。我错过了一个
connections['default'].commit()
用于插入