pymysql模塊用法

python關於mysql的API--pymysql模塊

pymsql是Python中操做MySQL的模塊,其使用方法和py2的MySQLdb幾乎相同。python

模塊安裝

1
pip install pymysql

執行sql語句

import pymysql

#添加數據

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='yyy')

cursor = conn.cursor()


# sql = """CREATE TABLE EMPLOYEE (
#          FIRST_NAME  CHAR(20) NOT NULL,
#          LAST_NAME  CHAR(20),
#          AGE INT,
#          SEX CHAR(1),
#          INCOME FLOAT )"""
# 
# cursor.execute(sql)

#row_affected = cursor.execute("create table t1(id INT ,name VARCHAR(20))")

#row_affected=cursor.execute("INSERT INTO t1(id,name) values (1,'alvin'),(2,'xialv')")

#cursor.execute("update t1 set name = 'silv2' where id=2")




#查詢數據
row_affected=cursor.execute("select * from t1")
one=cursor.fetchone()

# many=cursor.fetchmany(2)
# all=cursor.fetchall()



#scroll
#cursor.scroll(-1,mode='relative')  # 相對當前位置移動   (備註:參數:1是向下,-1是向上)

#cursor.scroll(2,mode='absolute') # 相對絕對位置移動


#更改獲取數據結果的數據類型,默認是元組,能夠改成字典等:conn.cursor(cursor=pymysql.cursors.DictCursor)


conn.commit()
cursor.close()
conn.close()



示例:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='oldboy123', db='s1')

# cursor = conn.cursor()
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

#用賦值的方式查看
# sql="create table kuaiwei(id int,name varchar(20));"
#
# cursor.execute(sql)

#執行命令,反回結果
# ret=cursor.execute("insert into kuaiwei VALUES (1,'linye')")
#
# print(ret)

ret=cursor.execute("select * from kuaiwei")
# print(cursor.fetchone())
# print(cursor.fetchall())
print(cursor.fetchmany(3))

#相對當前位置移動,-1是向上
# cursor.scroll(-1,mode="relative")

#相對當前位置移動,1是向下
# cursor.scroll(1,mode="relative")

#absolute 相對絕對位置移動
# cursor.scroll(1,mode="absolute")

# print(cursor.fetchone())

conn.commit()
cursor.close()
conn.close()

#mysql數據庫
mysql

mysql> select * from kuaiwei;
+------+-------+
| id | name |
+------+-------+
| 1 | alex |
| 2 | alvin |
| 1 | linye |
+------+-------+
3 rows in set (0.00 sec)sql

相關文章
相關標籤/搜索