簡體   English   中英

Django / Python Postgresql原始SQL問題

[英]Django/python postgresql raw sql issue

我對這個django原始sql請求感到困惑

setting.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表位,沒有。

這里發生了什么?

謝謝

UPDATE

現在問題已解決。 我想念一個

connections['default'].commit() 

用於插入

對於您的查詢, r[0]是一個intlong字段,而stdout.write需要一個字符串。

並且update語句可能未執行,因為在到達該語句之前您已收到異常,因此腳本執行結束。

我不明白您為什么要對這些查詢執行原始SQL語句,也不明白您為什么要使用write而不是打印,但是我想這不是您要問的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM