蓝$桉

导航

 

1. 基本代码如下:

1) #导入 mysql包

 import MySQLdb

 

2) #连接数据库,此处信息也可以放到配置文件

  db=MySQLdb.connect("localhost",“usename”,“userpw”,“dbname”,charset='utf8')

 

 3)#获取游标

 cursor=db.cursor()

 

4)#执行sql语句

 cursor.execute("select * form student")

 

5) #使用 fetchone() 获取一条数据

 info=cursor.fetchone()

 

6) #使用 fetchall() 获取全部数据

 datas=cursor.fetchall()

 #定义空列表

 name=[]

 id=[]

 #将查询出来的名字和id分别放入name列表和id列表中

 for data in datas:

  id.append=row[0]

  name.append=row[1]

 

2. 基础SQL语句:

 1)对表结构的操作(DDL)

  # 创建数据库

   create database db_name

  # 创建数据表

   create table table_name

  # 修改数据表

   alter table table_name    rename to  table_name_new    #修改表名

   alter table table_name    add column age int notnull       #增加列名

   alter table table_name    change age age_1      #修改列名

   alter table table_name    modify  age int(2)      #修改数据类型

   [note]: change用来字段重命名,不能修改字段类型和约束;
       modify不用来字段重命名,只能修改字段类型和约束

  # 删除数据表

  drop table table_name

 2)对表内容的操作(DML)

   # 查询语句

   select * from student where name='张三'

    # 修改语句

   update student set age=18 where name='张三'

    # 插入语句

   insert student (id,name) values('李四',‘17’)

    # 删除表数据

   delete form student where name='李四'

  

posted on 2020-05-14 11:18  蓝$桉  阅读(98)  评论(0编辑  收藏  举报