読者です 読者をやめる 読者になる 読者になる

HandlerSocket練習帳 - チラシの裏

MySQL Python

PythonでHandlerSocket経由でMySQLにアクセスする。今回はpyhsを使ってみた。

データベース名はsandboxで、テーブルは、

Create Table: CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL,
  `password` varchar(255) NOT NULL,
  `salt` varchar(40) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

のようなテーブル。

from pyhs import Manager

DB_NAME = 'sandbox'

hs = Manager(
    read_servers=[('inet', 'localhost', 9998)],
    write_servers=[('inet', 'localhost', 9999)],
    debug=False)

# SELECT id, username, password FROM user WHERE id=1
res = hs.get(DB_NAME, 'user', ['id', 'username', 'password'], '1')
print res

# SELECT password FROM user WHERE username='scott'
res = hs.find(DB_NAME, 'user', '=', ['id', 'password'], ['scott'], 'idx_username', 10)
print res

# SELECT id, name FROM user WHERE id >= 2 LIMIT 10
res = hs.find(DB_NAME, 'user', '>=', ['id', 'username'], ['2'], 'PRIMARY', 10)
print res

# UPDATE user SET password='tiger' WHERE username='scott'
res = hs.update(DB_NAME, 'user', '=', ['password'], ['scott'], ['tiger'], 'idx_username',
                return_original=True)
print res

# DELETE FROM user WHERE username='foo'
res = hs.delete(DB_NAME, 'user', '=', ['username'], ['foo'], 'idx_username',
                return_original=True)
print res

# INSERT INTO user(username, password, salt) VALUES ('foo', 'bar', 'baz')
res = hs.insert(DB_NAME, 'user', [('username', 'foo'), ('password', 'bar'), ('salt', 'baz')])
print res

HandlerSocket、使えるな。