数据库操作(补充)

import pymysql

# 1、连上数据库  账号、密码 ip 端口号 数据库

#2、建立游标

#3、执行sql

#4 、获取结果

# 5、关闭游标

#6、连接关闭

coon = pymysql.connect(

      host='XXXXX',user='jxz',passwd='123456',

      port=3306,db='jxz',charset='utf8'

      #port必须写int类型,

      #charset这里必须写utf8

)

cur = coon.cursor() #建立游标

# cur.execute('select * from stu;')#执行sql语句

# cur.execute('insert into stu (id,name,sex) VALUE (1,"牛寒阳","女");')

username = 'nhy'

pwd='123456'

sql = 'select * from nhy where name="%s"  and pwd = "%s "'%(username,pwd)   #查看该用户是否正确。

cur.execute(sql)

# select * from nhy where username="nhy" and pwd="xxxx";

# delete update insert

# coon.commit()  #必须得coomit

res = cur.fetchall()  #获取所有返回的结果

print(res)

if res:

  print('用户已存在')

else:

  print('用户不存在!')

cur.close()#关闭游标

coon.close()#关闭连接

import pymysql

def my_db(sql,port=3306,charset='utf8'):

  import pymysql

  host, user, passwd, db = '118.24.3.40','jxz','123456','jxz'

  coon = pymysql.connect(user=user,host=host,port=port,passwd=passwd,db=db,charset=charset)

  cur = coon.cursor(cursor=pymysql.cursors.DictCursor) #建立游标,指定cursor类型返回的是字典,可以dir查看方法,默认返回list(),现在里面的元素为字典的list。

  cur.execute(sql)#执行sql

  if sql.strip()[:6].upper()=='SELECT':

           # res = cur.fetchall()

     # res = cur.fetchone()  #最外层变为字典

**

cur = coon.cursor(cursor=pymysql.cursors.DictCursor)

建立游标的时候指定了游标类型,返回的就是一个字典了。

fetchall() #获取到这个sql执行的全部结果,它把数据库表里面的每一行数据放到一个list里面

     [ ['1','2','3']  ]   [{},{},{}]

fetchone() #获取到这个sql执行的一条结果,它返回就只是一条数据  多个时依次向下取值

如果sql语句执行的结果是多条数据的时候,那就用fetchall()

如果你能确定sql执行的结果就只有一条,那么就用fetchone()

**

           # fileds = []

           # for filed in cur.description:

           #      fileds.append(filed[0])    #用来取数据库的表头字段

            fileds = [ filed[0] for filed in cur.description ]  #和上面3行代码的意思是一样,(列表生成式)cur.description  二位数组会返回字段名,id和空等内容信息。

           print(fileds)

           # cur.fetchmany()  #能传入一个数,返回多少条数据

           res= 'xx'

  else:

           coon.commit()

           res = 'ok'

  cur.close()

  coon.close()

  return res

res = my_db('select * from users_info limit 10;')  #只显示10行

print(res)

猜你喜欢

转载自www.cnblogs.com/cslw5566/p/9026481.html