一开始遇到了许多问题 在pycharm中import mysql、MySQLdb都没有用,最后查了些资料,发现在python3.x中 已经改为了pip install MySQLClient
然后import MySQLdb就可以了
之后连接上数据库 可以做一些 简单的增删改操作
注意:增删改代码最好加try。。exception。。finally 进行检查
import MySQLdb
conn=MySQLdb.connect(host=‘127.0.0.1‘,port=3306,user=‘root‘,passwd=‘fanxiaoqian‘,db=‘test‘,charset=‘utf8‘)
cursor=conn.cursor()
cursor.execute(‘‘‘
create table if not EXISTS user
(
userid bigint(11) PRIMARY KEY ,
username VARCHAR(20)
)
‘‘‘)
for i in range(10):
cursor.execute("insert into user(userid,username) values(‘%d‘,‘%s‘)" %(int(i),‘name‘+str(i)))
conn.commit()
# res=cursor.fetchall()
# for row in res:
# print(row)
#
# sql=‘select * from user‘
# cursor.execute(sql)
# print(cursor.rowcount)
#
# rs = cursor.fetchone()
# print(rs)
#
# rs = cursor.fetchmany(3)
# print(rs)
# rs=cursor.fetchall()
# print(rs)
sql_insert = ‘insert into user(userid,username) values(10,"name10")‘
sql_update = ‘update user set username="name91" where userid=9‘
sql_delete = ‘delete from user where userid=3‘
cursor.execute(sql_insert)
print(cursor.rowcount)
cursor.execute(sql_update)
print(cursor.rowcount)
cursor.execute(sql_delete)
print(cursor.rowcount)
conn.commit()
参考博客 :https://www.cnblogs.com/itdyb/p/5700614.html