반응형
python 으로 MySQL 사용
CRUD
python terminal 에서 install
pip install mysql-connector-python
준비끝.
import
import mysql.connector
연결정보
mydb = mysql.connector.connect(
host="input_some.host.com_or_ip",
user="input_username",
passwd="input_password",
database="input_dbname"
)
select 문
cur = mydb.cursor()
cur.execute("select * from tbl_something where idx in (46,88,89,103,107)")
myresult = cur.fetchall()
for x in myresult:
print(x)
전체 소스
import mysql.connector
mydb = mysql.connector.connect(
host="192.168.1.23",
user="root",
passwd="mypassword",
database="testdb"
)
cur = mydb.cursor()
cur.execute("select * from tbl_something where tidx in (46,88,89,103,107)")
myresult = cur.fetchall()
for x in myresult:
print(x)
역시 파이썬은 간단하네요.
======= 예제들
하나만 조회하기
myresult = mycursor.fetchone()
print(myresult)
Insert 문
'''
연결정보생략
'''
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Delete 문
'''
연결정보생략
'''
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
Update 문
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
728x90
반응형
'Python' 카테고리의 다른 글
[Python] Dictionary Sort (정렬) lambda (2) | 2019.11.05 |
---|---|
[Python] Dictionary Filter (3) | 2019.11.05 |
Tensorflow 2.0 release 이후 설치 방법 (0) | 2019.10.21 |
[Python] python 설치 on Mac (0) | 2019.08.13 |
[python] Dictionary 의 특정 값의 sum, max, min 값 가져오기 (0) | 2019.02.15 |
댓글