【问题标题】:Django/python postgresql raw sql issueDjango/python postgresql 原始 sql 问题
【发布时间】:2013-10-22 17:59:09
【问题描述】:

我被这个 django raw 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 表中插入一行它没有插入。

这是怎么回事?

谢谢

更新

现在问题已解决。我错过了一个

connections['default'].commit() 

插入

【问题讨论】:

    标签: python sql django postgresql


    【解决方案1】:

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

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

    我不明白你为什么要为这些查询执行原始 SQL 语句,我不明白你为什么使用 write 而不是打印,但我想这不是你问的问题.

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 2012-03-16
      相关资源
      最近更新 更多