2016-12-26 1 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

테이블 이름은 user하지만 USER는 MySQL의에서 예약 된 키워드입니다. 오류가 원인 일 수 있습니다.

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

다음과 같이 finally 블록 구현하고 오류 응답을 받고 있는지 확인합니다. 다음

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

및 업데이트 장고 ORM을 사용 : 당신은 settings.py 파일에 데이터베이스에 대한 기본 매개 변수를 설정할 수 있습니다

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

,이 같은 :

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

사용자는 키워드입니다. 사용자는 키워드가 아닙니다. 동일한 사용자 테이블 내가 테이블에 데이터를 삽입하고 아무런 문제가 테이블에서 데이터를 선택하는 데 사용하고 있습니다. 데이터 업데이트가 문제입니다. –

+0

finally 블록에 마지막 두 줄을 넣고 오류 응답을 얻는 지 확인하십시오. – MYGz

+0

아직 오류가 발생하지 않았다 –

1
이 같은 조건 쿼리

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) 
관련 문제