import MySQLdb conn = MySQLdb.connect( user='root', passwd='', host='localhost', db='test') cur = conn.cursor() # cur.execute("DROP TABLE items") cur.execute(''' CREATE TABLE items( item_id INTEGER PRIMARY KEY AUTO_INCREMENT, name TEXT, price INTEGER ) ''') data = [('Banana', 300),('Mango', 640),('Kiwi', 280)] for i in data: cur.execute("INSERT INTO items(name,price) VALUES(%s,%s)", i) cur.execute("SELECT * FROM items") for row in cur.fetchall(): print(row)
[vagrant@localhost python]$ python3 app.py
Traceback (most recent call last):
File “app.py”, line 1, in
import MySQLdb
ImportError: No module named ‘MySQLdb’
なに?
mysqlclientを入れる
[vagrant@localhost python]$ pip3 install mysqlclient
Collecting mysqlclient
Downloading https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz (90kB)
100% |████████████████████████████████| 92kB 265kB/s
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient … done
Successfully installed mysqlclient-1.3.13
お!
[vagrant@localhost python]$ python3 app.py
(1, ‘Banana’, 300)
(2, ‘Mango’, 640)
(3, ‘Kiwi’, 280)