1,使用Python增加一个表


#导入用来操作数据库的模块

import pymysql


#建立连接数据库对象

conn=pymysql.connect(host='127.2.2.2',user='root',passwd='123456',db='records')


#建立游标

cur=conn.cursor()


#用游标里的方法执行sql语句

cur.execute("create table people(name char(20),height int(3),weight int(3))")


#语句执行完后关闭游标

cur.close()


#关闭到数据库的连接

conn.close()


以上代码执行完成后可以在数据库中查看,已经建立了一个people的表。


2,在表中插入一条数据。


#用游标里的方法执行sql语句

cur.execute("insert into people values('tom',110,34)")


#提交刚才所做的insert操作,让它生效

conn.commit()


3,修改表中的一条数据,将height改为177


#用游标里的方法执行sql语句

cur.execute("update people set height=177 where name='tom' ")


#提交刚才所做的insert操作,让它生效

conn.commit()


4,查询表中的数据


#用游标里的方法执行sql语句

cur.execute("select * from people ")


#fetchall方法可以将上面select执行的语句结果抓取下来。

print (cur.fetchall())


5,删除表中的数据


#用游标里的方法执行sql语句

cur.execute("delete from people where name='tom'")


#提交刚才所做的insert操作,让它生效

conn.commit()