import pymysql
coon=pymysql.connect(
host='118.XX.XX.40',user='XXX',passwd='123456',
port=3306,db='XXX',charset='utf8'
)
cur=coon.cursor()#建立游标
#执行sql
######优化SQL
username='nhy'
pwd='123456'
# sql='select * from stu where username="%s"'%(username)
sql='select * from nhy where name="%s" and pwd="%s"'%(username,pwd)
print(sql)
cur.execute(sql)
res=cur.fetchall() #获取所有返回的结果 元组list
# print(res)
if res:
print('用户不存在')
else:
print('用户已存在!')
cur.close()
coon.close()
数据库函数
def my_db(sql,port=3306,charset='utf8'):
import pymysql
host,user,passwd,db='118.XX.XX.XX','XXX','123456','XXX'
coon=pymysql.connect(
host=host,user=user,passwd=passwd,db=db,
port=port,charset=charset
)
# 建立游标,指定cursor类型返回的是字典
cur=coon.cursor(cursor=pymysql.cursors.DictCursor)
cur.execute(sql)
if sql.strip()[:6].upper()=='SELECT':
# res=cur.fetchall()
res = cur.fetchone()
# cur.fetchmany() #能传入一个数,返回多少条数据
else:
coon.commit()
res='ok'
cur.close()
coon.close()
return res
res=my_db('select * from stu limit 10; ')
print(res)
fetchall()
#获取到SQL执行的全部结果,它把数据库表里面的每一行数据放到一个LIST里面
# [['1','2','3']] [{},{},{}]
fetchone()#获取到这个SQL执行的一条结果,它返回的就只是一条数据
如果sql语句执行的结果是多条数据时,那就用fetchall()
如果sql语句执行的结果是一条数据时,那就用fetchone()
def my_db(sql,port=3306,charset='utf8'):
import pymysql
host,user,passwd,db='118.XX.XX.XX','XXX','123456','XXX'
coon=pymysql.connect(
host=host,user=user,passwd=passwd,db=db,
port=port,charset=charset
)
# 建立游标,指定cursor类型返回的是字典
cur=coon.cursor(cursor=pymysql.cursors.DictCursor)
cur.execute(sql)
if sql.strip()[:6].upper()=='SELECT':
print(cur.description)#获取字段的名字
# print(cur.fetchone())
# print(cur.fetchone())
# print(cur.fetchone())
res='xx'
else:
coon.commit()
res='ok'
cur.close()
coon.close()
return res
res=my_db('select * from stu limit 10; ')
print(res)
def my_db(sql,port=3306,charset='utf8'):
import pymysql
host,user,passwd,db='118.XX.XX.XX','XXX','123456','XXX'
coon=pymysql.connect(
host=host,user=user,passwd=passwd,db=db,
port=port,charset=charset
)
# 建立游标,指定cursor类型返回的是字典
cur=coon.cursor(cursor=pymysql.cursors.DictCursor)
cur.execute(sql)
if sql.strip()[:6].upper()=='SELECT':
fileds=[]
# for filed in cur.description:
# fileds.append(filed[0])
# 和上面3行代码的意思是一样,cur.description动态获取到表的字段
fileds=[fileds[0] for fileds in cur.description]
print(fileds)
res='xx'
else:
coon.commit()
res='ok'
cur.close()
coon.close()
return res
res=my_db('select * from stu limit 10; ')
print(res)