python 操作数据库1--连接、执行sql语句
2024-09-04 15:51:41
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2017/11/20 16:03
# @Author : lijunjiang
# @File : demo.py
import MySQLdb
# 连接数据库
# host 数据库IP
# port 数据库监听端口
# user 数据库用户
# passwd 用户密码
# db 数据库名
# charset 字符集 默认uft-8
# MySQLdb.Connect 方法
#comn=MySQLdb.Connect(host="11.11.11.11",user="python",passwd="python",db="python",charset="utf8",port=3306)
# 函数型式
def connect_mysql():
db_config = dict(host="11.11.11.11", port=3306, db="python", charset="utf8", user="python", passwd="python")
try:
cnx = MySQLdb.connect(**db_config)
except Exception as err:
raise err
return cnx
if __name__ == "__main__":
sql = "create table test(id int not null);"
cnx = connect_mysql() # 连接mysql
cns = cnx.cursor() # 创建一个游标对象
# print(dir(cnx))
try:
cns.execute(sql) # 执行 sql execute执行一条语句
cns.close() # 关闭游标
cnx.commit() # 提交操作
except Exception as err:
raise err
finally:
cnx.close() # 关闭连接
# 执行多条语
sql_many = 'insert into test(id) value (%s);'
param = []
for i in xrange(90,101):
param.append([str(i)])
# print(param)
cnx = connect_mysql()
cus = cnx.cursor()
try:
cus.executemany(sql_many,param) # executemany()接收一个sql语句,一个列表
# print(dir(cus))
cus.close()
except Exception as err:
raise err
finally:
cnx.close()
# 获取执行结果
sql_select = 'select * from test;'
cnx = connect_mysql()
cus = cnx.cursor()
try:
cus.execute(sql_select)
result_one = cus.fetchone() # fetchone() 获取一条结果
print("resutl1 {0}",format(result_one))
result_many = cus.fetchmany(3) # fetchmany(n) 获取n条结果
print("resutl1 {0}", format(result_many))
result_all = cus.fetchall() # fetchall() 获取所有结果
print("resutl1 {0}", format(result_all))
cus.close()
except Exception as err:
raise err
finally:
cnx.close()
mysql> select * from test;
+-----+
| id |
+-----+
| 90 |
| 91 |
| 92 |
| 93 |
| 94 |
| 95 |
| 96 |
| 97 |
| 98 |
| 99 |
| 100 |
+-----+
11 rows in set (0.00 sec)
最新文章
- ShowMessageFmt 用法
- javascript数据结构和算法
- GridView的 OnRowDataBound 事件用法
- Memcached和Redis对比和适用场景
- C#知识点有必要知会
- Selenium测试规划
- web HTML5 调用摄像头的代码
- 一次线上OOM故障排查经过
- js中内建对象
- Groovy简洁开发,我用到的简洁之处
- asp.net服务器向客户端弹出对话框,但不使页面边白板
- SuperSocket应用之FTP源码解析
- 69、django之Form组件
- Struts2 源码剖析 控制部分-----1
- 【English】五、颜色相关
- SQL Server2016安装
- c语言cgi笔记
- Java 4- Java 变量类型
- 51开发环境的搭建--KeilC51的安装及工程的创建
- [VTK]基于VTK的三维重建
热门文章
- WPF仿QQ聊天框表情文字混排实现
- python学习笔记十一:操作mysql
- 每天一个Linux命令(5):rm命令
- 【转载】全面解析Unity3D自动生成的脚本工程文件
- Opencv2.4.13.6安装包
- mongodb 部署
- SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'XXX' (13)
- 爬虫:Scrapy8 - Item Pipeline
- 微信小程序--动态添加class样式
- HTML5_纯JS实现上传文件显示文件大小,文件信息,上传进度_不使用JS库