ubuntu下mysql安装及python操作

来源:互联网 发布:ubuntu 拼音 编辑:程序博客网 时间:2024/05/21 08:38

mysql安装

1. sudo apt-get install mysql-server2. apt-get isntall mysql-client3.  sudo apt-get install libmysqlclient-dev登陆mysql数据库可以通过如下命令:mysql -u root -p

pymysql安装(python连接mysql)

pip3 install pymysql安装成功/usr/local/lib/python3.5/dist-packages会看到PyMySQL-0.7.11.dist-infopymysql如果使用pycharm 直接对应的python版本下在settings上安装插件即可超级方便

使用pymysql操作sql

#!/usr/bin/env pytho# -*- coding:utf-8 -*-import pymysql# 创建连接conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='database_name', charset='utf8')# 创建游标cursor = conn.cursor()# 执行SQL,并返回收影响行数effect_row = cursor.execute("select * from tabe_name")# 执行SQL,并返回受影响行数#effect_row = cursor.execute("update tb7 set pass = '123' where nid = %s", (11,))# 执行SQL,并返回受影响行数,执行多次#effect_row = cursor.executemany("insert into tb7(user,pass,licnese)values(%s,%s,%s)", [("u1","u1pass","11111"),("u2","u2pass","22222")])# 提交,不然无法保存新建或者修改的数据conn.commit()# 关闭游标cursor.close()# 关闭连接conn.close()

创建数据表

# 打开数据库连接db = pymysql.connect(host = '127.0.0.1',                     port = 3306,                     user = 'root',                     passwd = 'root',                     db='users',                     charset = 'utf8')#创建游标对象cursor = db.cursor()#使用 execute()方法执行SQL, 如果表存在则删除cursor.execute("drop table IF EXISTS employee")# 使用预处理语句创建表sql = '''      create table employee(       id int PRIMARY KEY NOT NULL auto_increment,       name CHAR(20) not null,       passwd CHAR(20),       age int,       sex char(1)      )      '''cursor.execute(sql)# 提交到数据库执行db.commit()#关闭游标 关闭数据库连接cursor.close()db.close()

插入数据

sql = "select * from employee \       where id = '%d'" \       % (1)try:    cursor.execute(sql)    results = cursor.fetchall()    for row in results:        id = row[0]        name = row[1]        passwd = row[2]        age = row[3]        sex = row[4]        print("id=%d, name=%s, passwd=%s, age=%d, sex=%c" % \              (id,name,passwd,age,sex))except:    print("Error: unable to fetch data")cursor.close()db.close()

更新数据

#更新操作sql = "update employee set age = age + 1 where sex = '%c'"\    % ('M')try:    effect_row = cursor.execute(sql)    print("effect_row:",effect_row)    db.commit()except:    db.rollback()cursor.close()db.close()

删除数据

# SQL 删除语句sql = "delete from employee where age = 20"print("1")try:    # 执行SQL语句    effect_row =    cursor.execute(sql)    print("effect_row:" , effect_row)    # 提交修改    db.commit()except:    print("except")    # 发生错误时回滚    db.rollback()

执行事务

执行事务事务机制可以确保数据一致性。事务应该具有4个属性:原子性、一致性、隔离性、持久性。这四个属性通常称为ACID特性。    原子性(atomicity)。一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。    一致性(consistency)。事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。    隔离性(isolation)。一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。    持久性(durability)。持续性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。 Python DB API 2.0 的事务提供了两个方法 commitrollback
原创粉丝点击