多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## MySQLdb模块 这个模块主要用于连接mysql数据库和执行SQL脚本 ### 安装扩展 使用这个模块需要安装扩展,可以使用yum安装或者pip安装 ``` yum install -y mysql-python # 或者 pip install mysql-python ``` --- ### 连接数据库 ``` # 导入模块 import MySQLdb # 连接数据库 conn = MySQLdb.connect(host='host', user='username', passwd='', db=) ``` ### 执行命令 ``` # 获得游标 cursor = conn.curosr() # 执行SQL cursor.execute('show databases') ``` ### 查看执行结果 ``` # 查看所有结果 cursor.fetchall() # 查看指定数目的结果 也可以指定cursor.arraysize=size cursor.fetchmany(size='size') # 一次查看一条结果 cursor.fetchone() ``` ### 提交 如果使用的是`innodb引擎`,则结束SQL时需要提交,innodb属于事务型引擎;如果是myISAM则不用。 ``` cursor.execute('commit') # 或者 conn.commit ``` ### 关闭数据库库连接 ``` cursor.close() ``` --- ### 补充:SQL注入 ``` # 这种写法会导致表t2被删除 cur.execute("insert into t2 values(%s, '%s')" % (5, 'acb\');drop table t2;')) ``` 应该采用这种写法 ``` cur.execute("insert into t1 values(%s, %s)", (5, 'acb\');drop table t2;')) ```