페이지

레이블이 mysql인 게시물을 표시합니다. 모든 게시물 표시
레이블이 mysql인 게시물을 표시합니다. 모든 게시물 표시

2019년 8월 10일 토요일

python mysql mysqlclient MySQLdb

설치

pip install mysqlclient


모듈 로드

import MySQLdb


데이터베이스 연결

connection = MySQLdb.connect(
    user="username",
    passwd="password",
    host="localhost",
    db="dbname",
    charset="utf8"
)

커서 추출

cursor = connection.cursor()

업데이트 쿼리

# create table note ( title varchar(100), content text )
cursor.execute("insert into note(title, content) values(%s,%s)", ("a", "b"))
connection.commit()

조회 쿼리

sql = "select * from note where title=%s"
cursor.execute(sql, ('a',))

for row in cursor.fetchall():
    print(row)  # ('a', 'b')

Dict 커서로 변경

cursor = connection.cursor(MySQLdb.cursors.DictCursor)

cursor.execute(sql, ('a',))
for row in cursor.fetchall():
    print(row)  # {'title': 'a', 'content': 'b'}
    print(row['title'], row['content'])     # a b

연결 종료

connection.close()

2016년 6월 8일 수요일

django 에서 mysql 사용하기

데이터베이스 이름을 db1
유저명을 user1
유저암호를 user1_pw

데이터베이스 추가 및 유저 추가

create database db1;
grant all privileges on db1.* to 'user1'@'127.0.0.1' identified by 'user1_pw';

127.0.0.1 는 데이터베이스 서버와 django 서버가 다른서버에 있다면 django 서버의 IP 를 입력합니다.

mysqlclient 설치 - https://github.com/PyMySQL/mysqlclient-python

$ sudo apt-get install libmysqlclient-dev
$ pip install mysqlclient

데이터베이스 설정 변경 - project/settings.py

DATABASES 항목을 찾아서 다음과 같이 수정합니다.
DATABASES = {
    'default':{
        'ENGINE':'django.db.backends.mysql',
        'NAME':'db1',
        'USER':'user1',
        'PASSWORD':'user1_pw',
        'HOST':'mysqlhost.example.com',
        'PORT':'3306',
    }
}

데이터베이스에 적용 및 수퍼유저 생성

$ python manage.py migrate
$ python manage.py createsuperuser

2014년 10월 22일 수요일

mysql 쿼리 결과 파일로 저장하기

mysql dbname -e "select * from tablename" -t > outfile.txt


  • -e : Execute command and quit.
  • -t : Output in table format.

2013년 9월 11일 수요일

Mysql Connector/J 5.1

Mysql Java 용 JDBC 드라이버 입니다.

http://dev.mysql.com/downloads/connector/j/
다운로드 링크입니다.

MSI Installer 설치 파일은 어디에 파일들을 설치했는지 알려주지도 않고 설치가 끝납니다.
불편해서 지우고 Select Platform: 을 Platform Independent 로 변경하고 압축파일을 받아서 사용했습니다.

압축을 해제하고 jar파일(mysql-connector-java-5.1.26-bin.jar)을 복사해서 사용했습니다.

mysql-connector-java-3.1.10-bin.jar 를 사용하다가 최신버전으로 변경하였는데요. 적용과정에서 한가지 문제가 되었던 부분이 있습니다.

메타데이터를 사용하는 부분입니다.
ResultSetMetaData rsmd = resultSet.getMetaData();

3버전에서 rsmd.getColumnName(no) 는 필드의 Alias 값을 반환했습니다.
5버전에서는 rsmd.getColumnLabel(no) 를 사용해야 Alias 값을 받을 수 있고 rsmd.getColumnName(no) 는 컬럼의 실제 이름값을 반환합니다.

예를 들면 아래와 같은 쿼리가 있다면
select a as b from table;

3버전에서 rsmd.getColumnName(no) 는 'b'
5버전에서 rsmd.getColumnName(no) 는 'a'
5버전에서 rsmd.getColumnLabel(no) 는 'b'
가 됩니다.