栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 连接mysql数据库进行操作

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 连接mysql数据库进行操作


1.MySQLdb 模块是用于Python链接Mysql数据库的接口,默认是没有安装的

[root@python ~]# yum  install  MySQL-python   -y


2.创建python脚本

[root@python ~]# cat mysql.py 

#!/usr/bin/env python

#-*- coding: UTF-8 -*-


import MySQLdb as mysql  #导入MySQLdb模块


db=mysql.connect(user='root',passwd='centos',db='test',host='localhost')  #连接数据库


cursor=db.cursor() #创建游标对象


sql='create table test(id int,name varchar(8));' #创建表


cursor.execute(sql) #执行sql语句


db.close() #关闭连接


3.执行脚本,进库查看是否成功

[root@python ~]# mysql -uroot -pcentos

mysql> use test;

Database changed

mysql> show tables;

+----------------+

| Tables_in_test |

+----------------+

| test           |

+----------------+

1 row in set (0.00 sec)

mysql> desc test;

+-------+------------+------+-----+---------+-------+

| Field | Type       | Null | Key | Default | Extra |

+-------+------------+------+-----+---------+-------+

| id    | int(11)    | YES  |     | NULL    |       |

| name  | varchar(8) | YES  |     | NULL    |       |

+-------+------------+------+-----+---------+-------+

2 rows in set (0.00 sec)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/224863.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号