import MySQLdb
#创建mysql数据库连接对象
connect = MySQLdb.connect(
#链接数据库的host主机地址,默认本地数据库使用localhost或者127.0.0.1进行链接,如果链接远程数据库,需要设置远程主机的ip地址
host = "localhost",
#mysql数据库的端口号
port = 3306,
#链接数据库的用户名
user = "root",
#链接数据库用户名的密码
passwd = "123456",
#数据库名称
db = "student",
#当数据中要写入中文字符,需要设置两个参数
use_unicode = True,
charset="utf8"
)
#创建游标
cursor = connect.cursor()
#创建表
#auto_increment设置id自增
create_table = "create table if not exists stu(id integer primary key auto_increment,name varchar(5),age integer ,phone varchar(11))"
#插入语句
insert_sql = "insert into stu(name,age,phone)values('张三',14,'11011011011')"
#删除语句
delete_sql = "delete from stu where id=1"
#修改
update_sql = "update stu set age=16 where id=2"
#查询
select_sql = "select * from stu"
res = cursor.execute(select_sql)
# print(cursor.fetchone())
# print(cursor.fetchmany(2))
print(cursor.fetchall())
#执行创建表的sql语句
cursor.execute(create_table)
# cursor.execute(insert_sql)
# cursor.execute(update_sql)
# cursor.execute(delete_sql)
connect.commit()
cursor.close()
connect.close()
python创建mysql表和对数据的增删改查
猜你喜欢
转载自blog.csdn.net/cp_123321/article/details/93196232
今日推荐
周排行