转自:http://drizzlewalk.blog.51cto.com/2203401/448874/
官网说明:
参考:http://mysql-python.sourceforge.net/MySQLdb.html
参考:http://mysql-python.sourceforge.net/MySQLdb-1.2.2/
yum install MySQL-python 最好先把python-devel安装
MySQL-python-1.2.3-0.3.c1.1.el6.x86_64.rpm
1、建立连接,MySQLdb的connect()方法
conn1 = MySQLdb.connect( host='host', user='user', passwd= 'password', db = 'dbname', port=3306, charset='utf8' ) ##################### host:需要连接MySQL的主机ip user:连接MySQL使用的用户名 password:连接使用的用户名密码 dbname:默认打开的数据库 port:端口,不需要引号 charset:字符集,如果输出有乱码,检查MySQL字符集和python接口的是否一致
unix_socket:socket链接
2、获取数据库操作游标(指针)
cur1 = conn1.cursor() ############### 因该模块底层其实是调用C API,所以需要先得到当前指向数据库的指针
3、对数据库的操作
>>> cur1 = conn1.cursor() >>> do1 = cur1.execute("select * from t1") >>> do1 56L >>> cur1.close() 也可以 >>> cur1 = conn1.cursor() >>> sql1 = "select * from t1" >>> do1 = cur1.execute(sql1) >>> do1 56L >>> cur1.close() ################## 在python的IDE界面会有返回值,返回值是返回结果的行数
4、取得结果
>>> cur1.fetchone() (10L, 'ba') fetchone(self):返回单独一行的结果 >>> cur1.fetchall() ((10L, 'ba'), (10L, 'ba'), (10L, 'ba'), (10L, 'ba'), (1L, 'XXX')) >>> cur1.fetchall()[-1] (1L, 'XXX') fetchall(self):返回全部结果集(所有行),类型是tuple元组,可以用索引取出单个结果 >>> cur1.fetchmany(3) ((10L, 'ba'), (10L, 'ba'), (10L, 'ba')) fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
5、关闭游标和连接
commit()
rollback()
cur.close()
con.close()
5、异常处理
异常类别:https://www.python.org/dev/peps/pep-0249/#exceptions
参考:http://blog.csdn.net/zyz511919766/article/details/20546237
def get_instance_connection(instance_ip, instance_port, instance_database=''): try: conect_object = db.connect(user = , passwd = '', host = instance_ip, port = int(instance_port), db= instance_database) cursor_object = conect_object.cursor() return {'status':0, 'conect_object':conect_object, 'cursor_object':cursor_object} except Exception,e: return {'status':99, 'info':str(e)}
6、调整警告级别
http://blog.csdn.net/hewy0526/article/details/7695989
http://docs.python.org/library/warnings.html
参考:
http://www.cnblogs.com/hzhida/archive/2012/08/02/2619848.html
http://www.oschina.net/code/snippet_16840_1811
http://zhidao.baidu.com/link?url=mR-vmXHlmXSVwGd6bcs0qR_6hbDHw48mS15Lt80PAkSrNvgQx3P00tZ5FMCx8FHGuSSyq9o8YfP9yoKdwd2Ena
http://www.linuxidc.com/Linux/2012-06/63620.htm
http://zhidao.baidu.com/link?url=fnFe5WTrlFknM0i0wxYfPyN9zeKF6KClwdSTUMuX3a-x8d5l7miI0qgvcsDbmaHM43SkKXBePv_5v4vbnA1BQK
DBUtil.PooledDB数据库连接池:
源码地址:http://www.webwareforpython.org/downloads/DBUtils/
参考:
http://developer.51cto.com/art/201003/189679.htm
1.1.1英文官网说明
http://www.webwareforpython.org/DBUtils/Docs/UsersGuide.html
0.9.4中文说明
安装:
python setup.py install
为了使用 PooledDB 模块,你首先需要通过创建 PooledDB 来设置数据库连接池,传递如下参数(官方的说明可以查看help(PooledDB)):
- creator: 可以生成 DB-API 2 连接的任何函数或 DB-API 2 兼容的数据库连接模块。
- mincached: 启动时开启的空连接数量(缺省值 0 意味着开始时不创建连接)
- maxcached: 连接池使用的最多连接数量(缺省值 0 代表不限制连接池大小)
- maxshared: 最大允许的共享连接数量(缺省值 0 代表所有连接都是专用的)如果达到了最大数量,被请求为共享的连接将会被共享使用。
- maxconnections: 最大允许连接数量(缺省值 0 代表不限制)
- blocking: 设置在达到最大数量时的行为(缺省值 0 或 False 代表返回一个错误;其他代表阻塞直到连接数减少)
- maxusage: 单个连接的最大允许复用次数(缺省值 0 或 False 代表不限制的复用)。当达到最大数值时,连接会自动重新连接(关闭和重新打开)
- setsession: 一个可选的SQL命令列表用于准备每个会话,如 ["set datestyle to german", ...]
- creator 函数或可以生成连接的函数可以接受这里传入的其他参数,例如主机名、数据库、用户名、密码等。你还可以选择传入creator函数的其他参数,允许失败重连和负载均衡
Once you have set up the connection pool you can request database connections from that pool: db = pool.connection() You can use these connections just as if they were ordinary DB-API 2 connections. Actually what you get is the hardened SteadyDB version of the underlying DB-API 2 connection. Please note that the connection may be shared with other threads by default if you set a non-zero maxshared parameter and the DB-API 2 module allows this. If you want to have a dedicated connection, use: db = pool.connection(shareable=False) You can also use this to get a dedicated connection: db = pool.dedicated_connection() If you don't need it any more, you should immediately return it to the pool with db.close(). You can get another connection in the same way. Warning: In a threaded environment, never do the following: pool.connection().cursor().execute(...) This would release the connection too early for reuse which may be fatal if the connections are not thread-safe. Make sure that the connection object stays alive as long as you are using it, like that: db = pool.connection() cur = db.cursor() cur.execute(...) res = cur.fetchone() cur.close() # or del cur db.close() # or del db
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?