-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlfrompy.py
More file actions
80 lines (66 loc) · 2.02 KB
/
sqlfrompy.py
File metadata and controls
80 lines (66 loc) · 2.02 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# coding:utf-8
# Connect to the database
import mysql.connector
from mysql.connector import errorcode
import settings
from datetime import date, datetime, timedelta
# mysql connection
try:
cnx = mysql.connector.connect(
host=settings.dbhost,
user=settings.dbuser,
password=settings.dbpassword,
db=settings.dbname,
)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
cur = cnx.cursor()
# show all tables in the database
def showtables(cursor):
# show tables in DB
query = "SHOW TABLES from " + settings.dbname + ";"
print(query)
#cursor.execute(query)
cursor.execute("SHOW TABLES;")
result = cursor.fetchall()
print(result)
# create tables in the database
def createtables(cursor):
TABLES = {}
TABLES['daily_pos'] = (
"CREATE TABLE `daily_pos` ("
" `isbn` char(13) NOT NULL,"
" `pos` int(3) NOT NULL,"
" `date` date NOT NULL"
") ENGINE=InnoDB")
# In python3, we shoule use 'items' instead of 'iteritems' in python2.
for name, ddl in TABLES.items():
try:
print("Creating table {}: ".format(name), end='')
cursor.execute(ddl)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("already exists.")
else:
print(err.msg)
else:
print("OK")
def insertdata(cursor):
add_pos = ("INSERT INTO daily_pos "
"(isbn, pos, date) "
"VALUES (%s, %s, %s)")
data_pos = ('0000000000000', '0', date(2016, 9, 9))
cursor.execute(add_pos, data_pos)
cnx.commit()
if __name__ == '__main__':
print('Hello!')
showtables(cur)
insertdata(cur)
# close the sql connection
cur.close()
cnx.close()