-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMySQL-sample.py
More file actions
53 lines (43 loc) · 1.06 KB
/
MySQL-sample.py
File metadata and controls
53 lines (43 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#! /usr/bin/python
import MySQLdb as mdb
import sys
USERNAME = 'root'
PASSWORD = '123456'
SERVER_IP = 'localhost'
PORT = '3306'
DATABASE_NAME = 'test_python'
TABLE_NAME = 'test'
try:
conn = mdb.connect(SERVER_IP, USERNAME, PASSWORD, DATABASE_NAME)
except Exception, e:
print e
sys.exit(1)
try:
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS test')
cur.execute('CREATE TABLE test(id INT PRIMARY KEY AUTO_INCREMENT, \
value VARCHAR(25))')
# Add
cur.execute('INSERT INTO test(value) VALUES(%s)', ('ab',))
#'''This a sample of executemany
cur.executemany('INSERT INTO test(value) VALUES(%s)', (
('d',),
('e',),
('f',),
))
#'''
# Delete
cur.execute('DELETE FROM test WHERE id=%s', (2,))
# Update
cur.execute('UPDATE test SET value=%s WHERE id=%s', ('abck', 3))
cur.execute('SELECT * FROM test')
print cur.fetchall()
# Search
conn.commit()
except mdb.Error, e:
print e
if conn:
cur.rollback()
finally:
if conn:
conn.close()