# pycharm 连接mysql import pymysql username = input("输入用户名:") pwd = input("输入密码:") # 建立连接 conn = pymysql.connect( host = 'localhost', user='root', password='', database='pymysql', port=3306, charset='utf8' ) # 创建游标 cur = conn.cursor() sql = 'select * from user(表名) where username(字段)="%s"'%(username) print(sql) ret = cur.execute(sql) print(ret) # 1 说明连接成功 #关闭游标 cur.close() conn.close()
插入
# 插入 import pymysql username = input("输入用户名:") password = input("输入密码:") # 建立连接 conn = pymysql.connect( host = 'localhost', user='root', password='', database='pymysql', port=3306, charset='utf8' ) # 创建游标 cur = conn.cursor() # sql = 'select * from user(表名) where username(字段)= "%s"'%(username) # print(sql) sql = """insert into user(表名)(id,username,password) values(null,%s,%s)""" cur.execute(sql,(username,password)) conn.commit() #关闭游标 cur.close() conn.close()
# 查找 import pymysql # 建立连接 conn = pymysql.connect( host = 'localhost', user='root', password='', database='pymysql', port=3306, charset='utf8' ) # 创建游标 cur = conn.cursor() # sql = 'select * from user(表名) where username(字段) ="%s"'%(username) # print(sql) # select username,password from user where id = 1 # select * from user sql = """ select * from user """ cur.execute(sql) # result = cur.fetchall() result = cur.fetchmany(2) print(result) #关闭游标 cur.close() conn.close()
# 删除 import pymysql # 建立连接 conn = pymysql.connect( host = 'localhost', user='root', password='', database='pymysql', port=3306, charset='utf8' ) # 创建游标 cur = conn.cursor() # sql = """ # delete from user where id= 1 # """ # cur.execute(sql) # conn.commit() sql = """ update user(表名) set username(字段)= 'aaa' where id(字段) = 2 """ cur.execute(sql) conn.commit() #关闭游标 cur.close() conn.close()