本文主要是介绍Python中使用Mysql(编码实践),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文档 或者看源码
http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb-module.html
开篇
在上一篇Python中使用Mysql(安装篇)中,我们为Python安装了支持MySQL数据库的MySQLdb包,这篇中写的是我工作中最常用到的几种情形。
虽然也支持在Python中创建表,之类的操作。但在实际中很少是通过程序去创建一个数据库或一张表的。 这些工作一般都是由公司的DBA来完成。所以对于研发来说, 对数据库最常做的事情包括查询,插入行,和更新行。在实际工作中,删除一些行的行为也是不常用的,因为删除了就不容易回来,当不需要一些数据时,通常有一个代表 可用和不可用的字段,比如叫 enable。 当想删除一行时候,把这一行的enable置成0 来代替删除的动作。
情形一,查询一行
#!/usr/local/bin/python
# coding:utf-8
import MySQLdbdb_handle = MySQLdb.connect(host = '10.10.10.10', user = 'root', passwd = '123456', db = 'test',port = 3306, charset = 'utf8') sql = "select * from test.user_info limit 1"
cur = db_handle.cursor( MySQLdb.cursors.DictCursor )
cur.execute( sql )
result = cur.fetchone()
cur.close()
db_handle.close()
print result['id']
cur = db_handle.cursor( MySQLdb.cursors.DictCursor )
它使得上面的result是一个字典的对象,可以直接用索引来访问对应的字段。
情形二,查询多行
#!/usr/local/bin/python
# coding:utf-8
import MySQLdbdb_handle = MySQLdb.connect(host = '10.10.0.10', user = 'root', passwd = '123456', db = 'test',port = 3306, charset = 'utf8')sql = "select * from user_info limit 3"
cur = db_handle.cursor( MySQLdb.cursors.DictCursor )
cur.execute( sql )
result = cur.fetchall()
cur.close()
db_handle.close()if not result :for row in result:print row['id']
<pre name="code" class="python"><strong>if result == None :</strong>
<strong>if not result :</strong>
情形三,插入或者更新一行
#!/usr/local/bin/python
# coding:utf-8
import MySQLdbdb_handle = MySQLdb.connect(host = '10.10.10.10', user = 'root', passwd = '123456', db = 'test',port = 3306, charset = 'utf8')sql = "insert into fruit values ('','apple','fruit','red')"
cur = db_handle.cursor( MySQLdb.cursors.DictCursor )
cur.execute( sql )
db_handle.commit()
cur.close()
db_handle.close()
这篇关于Python中使用Mysql(编码实践)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!