我采用的是MySQLdb操作的MYSQL数据库。先来一个简单的例子吧:

1
2
3
4
5
6
7
8
9
10
import MySQLdb
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)
    cur=conn.cursor()
    cur.execute('select
* from user'
)
    cur.close()
    conn.close()
except MySQLdb.Error,e:
     print "Mysql
Error %d: %s"
 % (e.args[0],
e.args[
1])

  请注意修改你的数据库,主机名,用户名,密码。

下面来大致演示一下插入数据,批量插入数据,更新数据的例子吧:

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
import MySQLdb
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
    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 iin 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()这句来提交事务,要不然不能真正的插入数据。

运行之后我的MySQL数据库的结果就不上图了。

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
28
29
30
31
32
33
import MySQLdb
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
    cur=conn.cursor()
     
    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 rin results:
        print r
 
    print '=='*10
    cur.scroll(0,mode='absolute')
 
    results=cur.fetchall()
    for rin 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])

  运行结果就不贴了,太长了。

查询后中文会正确显示,但在数据库中却是乱码的。经过我从网上查找,发现用一个属性有可搞定:

在Python代码

conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 中加一个属性:

 改为:

conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8') 

charset是要跟你数据库的编码一样,如果是数据库是gb2312 ,则写charset='gb2312'。

下面贴一下常用的函数:

然后,这个连接对象也提供了对事务操作的支持,标准的方法

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条.

参考资料:

MySQLdb‘s
user guide

package
MySQLdb

转自:http://www.cnblogs.com/rollenholt/archive/2012/05/29/2524327.html

附:c与python对应api

MySQL
C API function mapping

C API _mysql
mysql_affected_rows() conn.affected_rows()
mysql_autocommit() conn.autocommit()
mysql_character_set_name() conn.character_set_name()
mysql_close() conn.close()
mysql_commit() conn.commit()
mysql_connect() _mysql.connect()
mysql_data_seek() result.data_seek()
mysql_debug() _mysql.debug()
mysql_dump_debug_info conn.dump_debug_info()
mysql_escape_string() _mysql.escape_string()
mysql_fetch_row() result.fetch_row()
mysql_get_character_set_info() conn.get_character_set_info()
mysql_get_client_info() _mysql.get_client_info()
mysql_get_host_info() conn.get_host_info()
mysql_get_proto_info() conn.get_proto_info()
mysql_get_server_info() conn.get_server_info()
mysql_info() conn.info()
mysql_insert_id() conn.insert_id()
mysql_num_fields() result.num_fields()
mysql_num_rows() result.num_rows()
mysql_options() various options to _mysql.connect()
mysql_ping() conn.ping()
mysql_query() conn.query()
mysql_real_connect() _mysql.connect()
mysql_real_query() conn.query()
mysql_real_escape_string() conn.escape_string()
mysql_rollback() conn.rollback()
mysql_row_seek() result.row_seek()
mysql_row_tell() result.row_tell()
mysql_select_db() conn.select_db()
mysql_set_character_set() conn.set_character_set()
mysql_ssl_set() ssl option to _mysql.connect()
mysql_stat() conn.stat()
mysql_store_result() conn.store_result()
mysql_thread_id() conn.thread_id()
mysql_thread_safe_client() conn.thread_safe_client()
mysql_use_result() conn.use_result()
mysql_warning_count() conn.warning_count()
CLIENT_* MySQLdb.constants.CLIENT.*
CR_* MySQLdb.constants.CR.*
ER_* MySQLdb.constants.ER.*
FIELD_TYPE_* MySQLdb.constants.FIELD_TYPE.*
FLAG_* MySQLdb.constants.FLAG.*

mysql的python api的更多相关文章

  1. 初识Django —Python API接口编程入门

    初识Django —Python API接口编程入门 一.WEB架构的简单介绍 Django是什么? Django是一个开放源代码的Web应用框架,由Python写成.我们的目标是用Python语言, ...

  2. Appium python API 总结

    Appium python api 根据testerhome的文章,再补充一些文章里面没有提及的API [TOC] [1]find element driver 的方法 注意:这几个方法只能通过sel ...

  3. The novaclient Python API

    The novaclient Python API Usage First create a client instance with your credentials: >>> f ...

  4. 在Ubuntu上安装Mysql For Python

    安装: 首先安装pip,并且把pip更新到最小版本 apt-get install python-pip pip install -U pip 安装mysql开发包 apt-get install p ...

  5. Snippet: Fetching results after calling stored procedures using MySQL Connector/Python

    https://geert.vanderkelen.org/2014/results-after-procedure-call/ Problem Using MySQL Connector/Pytho ...

  6. How to Access MySQL with Python Version 3.4

    http://askubuntu.com/questions/630728/how-to-access-mysql-with-python-version-3-4 How to Access MySQ ...

  7. #MySQL for Python(MySQLdb) Note

    #MySQL for Python(MySQLdb) Note #切记不要在python中创建表,只做增删改查即可. #步骤:(0)引用库 -->(1)创建连接 -->(2)创建游标 -- ...

  8. Openstack python api 学习文档 api创建虚拟机

    Openstack python api 学习文档 转载请注明http://www.cnblogs.com/juandx/p/4953191.html 因为需要学习使用api接口调用openstack ...

  9. Installing MySQL Connector/Python using pip v1.5

    The latest pip versions will fail on you when the packages it needs to install are not hosted on PyP ...

随机推荐

  1. gSoap工具wsdl2h及soapcpp2指令汇总

    gSoap开发包的下载地址http://sourceforge.net/projects/gsoap2,在bin目录下提供了两个工具: 1:wsdl2h:The gSOAP wsdl2h tool i ...

  2. 关于glibc中的res_init()函数

    /* * Set up default settings.  If the configuration file exist, the values * there will have precede ...

  3. windows程序设计(三)

    MFC所有封装类一共200多个,但在MFC的内部技术不只是简单的封装 MFC的内部总共有六大关键技术,架构起了整个MFC的开发平台 一.MFC的六大关键技术包括: a).MFC程序的初始化过程 b). ...

  4. GetClientRect

    这个函数好像就是对应于视口的,获取视口的宽高 #include <windows.h> LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPAR ...

  5. java 线程的中断

    Example12_6.java public class Example12_6 { public static void main(String args[]) { ClassRoom room6 ...

  6. 使用Emmet加速Web前端开发

    Emmet插件以前被称作为Zen Coding,是一个文本编辑器的插件,它可以帮助您快速编写HTML和CSS代码,从而加速Web前端开发.早在2009年,Sergey Chikuyonok写过一篇文章 ...

  7. cakephp 的事件系统(Getting to grips with CakePHP’s events system), 基于观察者模式

    This article was written about CakePHP 2.x and has been untested with CakePHP 3.x CakePHP seems to g ...

  8. android-------手写签名系统的设计与实现之实现画笔设置

    引自:http://www.xuebuyuan.com/1754358.html 既然我们实现了画布和画笔,也实现了手写,为了提高可用性,我们增加了对画笔风格的设置功能,这样就可以根据自己的需要选择画 ...

  9. iOS触摸事件深入

    转载自:http://www.cnblogs.com/wengzilin/p/4720550.html 概述 本文主要解析从我们的手指触摸苹果设备到最终响应事件的整个处理机制.本质上讲,整个过程可以分 ...

  10. 用批处理文件删除n天前的文件

    原文:http://blog.csdn.net/leehq/archive/2007/08/03/1723743.aspx 公司服务器用来备份数据的硬盘过段时间就会被备份文件占满,弄得我老是要登录到服 ...