學習如何在python中使用MySQL
阿新 • • 發佈:2018-01-27
idt 技術 insert exce prim python select hal width
一開始遇到了許多問題 在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
學習如何在python中使用MySQL