ITPub博客

首页 > IT职业 > IT职场 > Python 连接mysql数据库进行操作

Python 连接mysql数据库进行操作

IT职场 作者:at_1 时间:2021-09-09 09:29:20 0 删除 编辑


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)


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1817/viewspace-2803610/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-26

  • 博文量
    265
  • 访问量
    12477