标签:select 客户端 HERE mysql imp scroll 连接 输入 database
PYMYSQLimport pymysql
client = 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语句
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条信息
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() # 关闭连接
标签:select 客户端 HERE mysql imp scroll 连接 输入 database
原文地址:http://blog.51cto.com/13764714/2165998