Python在Django中直接操作Mysql的方法
更改Django项目的settings.py
添加DATABASES
| DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysite', 'USER': 'root', 'PASSWORD': 'nhce111', 'HOST': '127.0.0.1', } }
|
创建连接
| >>> import MySQLdb >>> conn = MySQLdb.connect(host = '127.0.0.1',port = 3306,user = 'root',passwd = 'nhce111',db = 'mysite',charset='utf8')
|
操作数据库增删改查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| try: cur=conn.cursor() cur.execute('create database if not exists python') conn.select_db('python') cur.execute('create table test(id int,info varchar(20))') value=[1,'hi rollen'] cur.execute('insert into test values(%s,%s)',value) values=[] for i in range(20): values.append((i,'hi rollen'+str(i))) cur.executemany('insert into test values(%s,%s)',values) cur.execute('update test set info="I am rollen" where id=3') conn.commit() cur.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
|
请注意一定要有 conn.commit()
这句来提交事务,要不然不能真正的插入数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| conn.select_db('python') count=cur.execute('select * from test') print 'there has %s rows record' % count result=cur.fetchone() print result print 'ID: %s info %s' % result results=cur.fetchmany(5) for r in results: print r print '=='*10 cur.scroll(0,mode='absolute') results=cur.fetchall() for r in results: print r[1] conn.commit() cur.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
|
cur.close()
conn.close()
执行操作结束之后,一定要关闭查询和链接。
查看数据库中的数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| '''count中得到的是usertable的元组数量''' >>> count=cur.execute('select * from usertable') >>> print count 3 '''执行查询''' >>> cur.execute("select * from usertable") 3L '''捕捉(fetch)所有查询结果到results''' >>> rusults = cur.fetchall() >>> print results (('100', '1000'), ('200', '2000'), ('300', '3000')) '''results是一个元组''' >>> type(results) <type 'tuple'> '''利用下标来定位数据''' >>> results[0][0] '100' >>> results[0][1] '1000'
|
常用函数整理
| commit() 提交 rollback() 回滚
cursor用来执行命令的方法: callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数 execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数 executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数 nextset(self):移动到下一个结果集
cursor用来接收返回值的方法: fetchall(self):接收全部的返回结果行. fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据. fetchone(self):返回一条结果行. scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.
|
转载链接