2016-12-26 158 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)