Python+Django数据库配置及使用——执行原始SQL - JRoger
Python+Django数据库配置及使用——执行原始SQL
开发环境
OS:Windows Server 2012
Python:2.7.5
Django:1.5.2
通过 settings.py 配置数据库
DATABASES = { \'default\': { #\'ENGINE\': \'django.db.backends.\', # Add \'postgresql_psycopg2\', \'mysql\', \'sqlite3\' or \'oracle\'. \'ENGINE\': \'django.db.backends.sqlite3\', #添加数据库引擎;选项[\'postgresql_psycopg2\', \'mysql\', \'sqlite3\' or \'oracle\']. \'NAME\': \'F:/TestPython/blog/blog/db/data.db\', # 数据库文件的路径. # The following settings are not used with sqlite3: # 下面的配置不适用于sqlite3: \'USER\': \'\', # 数据库登陆用户名 \'PASSWORD\': \'\', # 数据库登陆密码 \'HOST\': \'\', # Empty for localhost through domain sockets or \'127.0.0.1\' for localhost through TCP. # 主机名 \'PORT\': \'\', # Set to empty string for default. # 端口号 } }
使用数据库——查询
首先引入数据库模块
from django.db import connection
假设我的data.db数据库里面又一张名为 Customer 的表;接下来执行查询:
data = [] cursor = connection.cursor() cursor.execute(\'select * from customer\') for row in cursor.fetchall(): data.append(row[0])
正常情况下这个执行将会成功。row[0] 表示的是取 Customer 表的第一列的值。
使用数据库——更新
首先引入数据库模块
from django.db import connection,transaction
假设同上,接下来执行更新:
cursor = connection.cursor() cursor.execute("update customer set customername = \'%s\',tel = \'%s\' where Id = 1"%(un,tel)) transaction.commit_unless_managed() #记得提交事务
总结
对数据库的操作无非 CRUD ,没有什么好介绍的。其他数据库的使用类似,若 Python 没有集成,可能需要再下载对应数据库的驱动模块。还有添加和删除没有写,其实有了更新剩下这两个就很easy了。