반응형
MySQL 데이터베이스에 정수 188과 90을 삽입하고 싶지만 다음 코드가 작동하지 않습니다.
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="engy1")
x = conn.cursor()
x.execute("SELECT * FROM anooog1")
x.execute (" INSERT INTO anooog1 VALUES ('%s','%s') ", (188,90))
row = x.fetchall()
왜 작동하지 않습니까?
해결 방법
#Server Connection to MySQL:
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="engy1")
x = conn.cursor()
try:
x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
conn.commit()
except:
conn.rollback()
conn.close()
나를 위해 일하는 수정 :
>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>>
>>> #setup cursor
... cursor = db.cursor()
>>>
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>>
>>> sql = """CREATE TABLE anooog1 (
... COL1 INT,
... COL2 INT )"""
>>> cursor.execute(sql)
0L
>>>
>>> #insert to table
... try:
... cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
... db.commit()
... except:
... db.rollback()
...
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>>
>>> db.close()
mysql의 테이블;
mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
| 188 | 90 |
+------+------+
1 row in set (0.00 sec)
mysql>
참조 페이지 https://stackoverflow.com/questions/5687718
반응형
'파이썬' 카테고리의 다른 글
파이썬 Python의 시간대 이름에서 UTC 오프셋 가져 오기 (0) | 2020.10.05 |
---|---|
파이썬 How to programmatically make a horizontal line in Qt (0) | 2020.10.05 |
파이썬 일반 및 유니 코드 빈 문자열에 대해 Python에서 "not None"테스트를 수행하는 가장 좋은 방법은 무엇입니까? (0) | 2020.10.05 |
파이썬 튜플에 대한 zip 함수 도움말 (0) | 2020.10.05 |
파이썬 Python dict를 kwargs로 변환 하시겠습니까? (0) | 2020.10.05 |
댓글