2016-12-26 48 views
-1

如何通過django更新mysql數據?我也沒有收到任何錯誤。如何使用django更新mysql數據?

views.py

def update_db_data(request): 
    conn = MySQLdb.connect(host= "localhost", user="test_user", passwd="test_pwd",db="myproject") 
    cursor = conn.cursor() 
    try: 
     cursor.execute("UPDATE user SET user_name = 'test'") 
     print("sucess") 
     html = "<html><body>sucess</body></html>" 
     conn.commit() 
    except: 
     print("fail") 
     html = "<html><body>fail</body></html>" 
     conn.rollback() 
    conn.close() 
    return HttpResponse(html) 

請告訴我哪裏是我的代碼的問題。 如何做條件更新?

eg:- UPDATE user SET user_name = 'test' where id =2; 
+0

您可以使用Django-ORM爲這個簡單的查詢。爲什麼不使用它? –

回答

2

你的表名是userUSER是MySQL中的保留關鍵字。也許這是導致錯誤。

http://dev.mysql.com/doc/refman/5.7/en/keywords.html

落實finally塊如下,看看你所得到的錯誤響應。

def update_db_data(request): 
    conn = MySQLdb.connect(host= "localhost", user="test_user", passwd="test_pwd",db="myproject") 
    cursor = conn.cursor() 
    try: 
     cursor.execute("UPDATE user SET user_name = 'test'") 
     print("sucess") 
     html = "<html><body>sucess</body></html>" 
     conn.commit() 
    except: 
     print("fail") 
     html = "<html><body>fail</body></html>" 
     conn.rollback() 
    finally: 
     conn.close() 
     return HttpResponse(html) 
+0

USER是關鍵字..用戶不是關鍵字。我正在使用相同的用戶表來插入數據到表中並從表中選擇數據沒有問題。更新數據是個問題。請用這個 –

+0

幫我解決'finally'中的最後兩行,看看你是否得到了錯誤響應。 – MYGz

+0

仍然沒有得到任何錯誤 –

1

對於這樣的條件查詢:

UPDATE user SET user_name = 'test' where id =2; 

可以在settings.py文件中設置默認參數數據庫,就像這樣:

DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.mysql', 
     'NAME': 'myproject', 
     'USER': 'test_user', 
     'PASSWORD': 'test_pwd', 
     'HOST': 'localhost', 
    } 
} 

然後使用Django ORM進行更新user_name,

from django.contrib.auth.models import User 
def update_db_data(request): 

    try: 
     user_obj = User.objects.get(id = 2) 
     user_obj.user_name = "test" 
     user_obj.save() 
     print("sucess") 
     html = "<html><body>sucess</body></html>" 

    except: 

     print("fail") 
     html = "<html><body>fail</body></html>" 

    return HttpResponse(html)