1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# SQLite -------------------------------------------------------- import sqlite3 con = sqlite3.connect("dat.sqlite") # sqlite3.connect(":memory:") cur = con.cursor() cur.execute("create table if not exists tbl (id integer primary key, name text)") # int だと自動採番しない con.commit() cur.execute("insert into tbl (name) values ('taro')") con.commit() cur.execute("select * from tbl") print(cur.fetchall()) cur.close() con.close() # MySQL -------------------------------------------------------- # pip install mysql-connector-python import mysql.connector # DBを指定しない場合 con = mysql.connector.connect(host="localhost",user="root",password="1234") cur = con.cursor() cur.execute("create database if not exists test_db") con.commit() cur.close() con.close() # DBを指定 con = mysql.connector.connect(host="localhost",user="root",password="1234",database="test_db") cur = con.cursor() cur.execute("create table if not exists tbl (id int not null auto_increment, name varchar(255) not null, primary key(id))") con.commit() cur.execute("insert into tbl (name) values ('taro')") con.commit() cur.execute("select * from tbl") for r in cur: print(r) cur.close() con.close() |