python 基础 9.3 mysql 数据操作

#/usr/bin/python
#coding=utf-8
#@Time   :2017/11/21 0:20
#@Auther :liuzhenchuan
#@File   :mysql 数据操作.py
import MySQLdb
 
 
def connect_mysql():
    db_config={
        'host':'192.168.16.70',
        'port':3306,
        'user':'root',
        'db':'python',
        'passwd':'123123',
        'charset':'utf8'
    }
    try:
        cnx=MySQLdb.connect (**db_config)
    except Exception as e:
        raise e
    return  cnx
connect_mysql()
# print connect_mysql()
if __name__ == "__main__":
    sql = 'create table test(id int not null); insert into test(id) values (100);'
    cnx = connect_mysql()
    #查看链接数据库cnx 的方法
    #cursor 游标  execute 执行
    # print dir(cnx)
    cus = cnx.cursor()
    try:
        #执行游标
        cus.execute(sql)
        #关闭游标
        cus.close()
        #mysql 提交
        cnx.commit()
    except Exception as e:
        raise e
        #有异常进行回滚
        cnx.rollback()
    finally:
        #没有异常关闭连接
        cnx.close()
 
 
linux系统登录mysql进行查看,创建了test表,插入了语句
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| cactidb            |
| mysql              |
| performance_schema |
| python             |
| test               |
+--------------------+
6 rows in set (0.00 sec)
 
mysql> use python;
Database changed
mysql> show tables;
+------------------+
| Tables_in_python |
+------------------+
| employees        |
| test             |
+------------------+
2 rows in set (0.00 sec)
mysql> select *from test;
+-----+
| id  |
+-----+
| 100 |
+-----+
1 row in set (0.00 sec)
 
 
 
 
原文地址:https://www.cnblogs.com/lzcys8868/p/7869088.html