gpt4 book ai didi

python - Django/python postgresql 原始 sql 问题

转载 作者:行者123 更新时间:2023-11-29 13:33:02 24 4
gpt4 key购买 nike

我对这个 django 原始 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() 

插入

最佳答案

对于您的查询,r[0] 是一个intlong 字段,而stdout.write 需要一个字符串。

并且更新语句可能没有执行,因为您在到达该语句之前收到异常,因此您的脚本执行结束。

我不明白你为什么要为这些查询做原始 SQL 语句,我不明白你为什么要使用 write 而不是 print,但我想那不是你问过的问题。

关于python - Django/python postgresql 原始 sql 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19372616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com