使用pymysql的方法
本文主要给大家简单讲讲使用pymysql的方法,相关专业术语大家可以上网查查或者找一些相关书籍补充一下,这里就不涉猎了,我们就直奔主题吧,希望使用pymysql的方法这篇文章可以给大家带来一些实际帮助。
PYMYSQLimport pymysqlclient = pymysql.connect( ip='127.0.0.1', # IP port=3306, # 端口 user='root', # 账号 password='', # 密码 database='t1', # 库 charset='utf8' # 字符编码)cursor = client.cursor(pymysql.cursors.DictCursor) # 拿到游标,将拿到的信息转换成字典user_info = [ (3, "alex"), (4, "lxx"), (5, "yxx")]# for user in user_info:# sql = 'insert into t1 values(%s,"%s");' % (user[0], user[1])# res = cursor.execute(sql) # 拼接sql语句还有一种简单的操作可以取代上面的for 循环增加一条数据到数据库
sql = 'insert into t1 values(%s,"%s")'cursor.executemany(sql, user_info)删除一条信息
cursor.execute('delete from t1 where id=3;')更改信息
cursor.execute('update t1 set password="12345" where name ="lxx";')查询语句
user_name = input('请输入账号名:').strip()user_password = input('请输入密码:').strip()sql = 'select id from user where name=%s and pwd=%s;'rows = cursor.execute(sql, (user_name, user_password))if rows: print('登陆成功')else: print('账号或者密码错误')查询语句把结果拿到
sql = 'select id from user where id>3;'rows = cursor.execute(sql)print(cursor.fetchall()) # 全部拿到,拿过一次第二次拿就没有print(cursor.fetchone()) # 拿一条信息print(cursor.fetchmany(2)) # 拿2条信息控制指针,有2种方式(这样就可以实现重复读取信息)
cursor.scroll(0, mode='absolute') # 绝对位置移动(从行首开始)cursor.scroll(3, mode='relative') # 相对当前位置移动(相对当前的位置往后移动3条信息)try: cursor.execute(sql) cursor.execute(sql) cursor.execute(sql) client.commit()except Exception as e: client.rollback() # 回溯, 如果上面的sql语句出现了错误那么就会回溯到没有插入数据的时候client.commit() # 要想成功执行SQL语句,必须调用commit插入到数据库cursor.close() # 关闭MYSQL客户端
client.close() # 关闭连接
使用pymysql的方法就先给大家讲到这里,对于其它相关问题大家想要了解的可以持续关注我们的行业资讯。我们的板块内容每天都会捕捉一些行业新闻及专业知识分享给大家的。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。