回答編集履歴

2 edit

mkgrei

mkgrei score 8385

2017/11/30 18:49  投稿

愚直に書いてみるのはどうでしょう。
with文が煩雑ですが。
```python
import MySQLdb
params = {'host' : "localhost",
         'db' : "test",
         'user' : "root",
         'passwd' : "hoge",
         'charset' : "utf8"}
n = 0
def update():
 with MySQLdb.connect(**params) as connector:
   cursor = connector.cursor()
 with MySQLdb.connect(**params) as cursor:
   sql = "insert into test(id) value("+ n +")"
   cursor.execute(sql)
   connector.commit()  
 n += 1
def select():
 with MySQLdb.connect(**params) as connector:
   cursor = connector.cursor()
 with MySQLdb.connect(**params) as cursor:
   sql = "select * from test"
   cursor.execute(sql)
   result = cursor.fetchall()
 print(result)
```
参考
https://qiita.com/fukkyy/items/759b25d72eb20ac2ccbe
1 add

mkgrei

mkgrei score 8385

2017/11/30 18:46  投稿

愚直に書いてみるのはどうでしょう。
with文が煩雑ですが。
```python
import MySQLdb
params = {'host' : "localhost",  
         'db' : "test",  
         'user' : "root",  
         'passwd' : "hoge",  
         'charset' : "utf8"}  
n = 0
def update():
 with MySQLdb.connect(host="localhost", db="test", user="root", passwd="hoge", charset="utf8") as connector:
 with MySQLdb.connect(**params) as connector:
   cursor = connector.cursor()
   sql = "insert into test(id) value("+ n +")"
   cursor.execute(sql)
   connector.commit()
 n += 1
def select():
 with MySQLdb.connect(host="localhost", db="test", user="root", passwd="hoge", charset="utf8") as connector:
 with MySQLdb.connect(**params) as connector:
   cursor = connector.cursor()
   sql = "select * from test"
   cursor.execute(sql)
   result = cursor.fetchall()
 print (result)
 print(result)
```
参考
https://qiita.com/fukkyy/items/759b25d72eb20ac2ccbe

思考するエンジニアのためのQ&Aサイト「teratail」について詳しく知る