Reference: Using MySQL from Python
# coding: utf-8
import MySQLdb
def main():
conn = MySQLdb.connect(
user='testuser',
passwd='testuser',
host='192.168.33.3',
db='testdb'
)
c = conn.cursor()
#Create table sql = 'create table test (id int, content varchar(32))' c.execute(sql) print ('* create test table \ n')
#Get table list sql = 'show tables' c.execute(sql) print ('===== table list =====') print(c.fetchone())
#Record registration sql = 'insert into test values (%s, %s)' c.execute (sql, (1,'hoge')) # 1 only datas = [ (2, 'foo'), (3, 'bar') ] c.executemany (sql, datas) # Multiple print ('\ n * Register 3 records \ n')
#Get record sql = 'select * from test' c.execute(sql) print ('===== record =====') for row in c.fetchall(): print('Id:', row[0], 'Content:', row[1])
#Delete record sql = 'delete from test where id=%s' c.execute(sql, (2,)) print ('\ n * delete record with id 2 \ n')
#Get record sql = 'select * from test' c.execute(sql) print ('===== record =====') for row in c.fetchall(): print('Id:', row[0], 'Content:', row[1])
#Save changes to database conn.commit()
c.close()
conn.close()
if __name__ == '__main__':
main()
Execution result
===== Table list ===== ('test',)
===== Record ===== Id: 1 Content: hoge Id: 2 Content: foo Id: 3 Content: bar
===== Record ===== Id: 1 Content: hoge Id: 3 Content: bar
Recommended Posts