-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode1.txt
More file actions
82 lines (63 loc) · 2.23 KB
/
code1.txt
File metadata and controls
82 lines (63 loc) · 2.23 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
81
82
import logging
log = logging.getLogger()
log.setLevel('INFO')
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))
log.addHandler(handler)
from datetime import datetime
import time
from cassandra import ConsistencyLevel
from cassandra.cluster import Cluster
from cassandra.query import SimpleStatement
KEYSPACE = "testkeyspace"
def main():
cluster = Cluster(['127.0.0.1'])
session = cluster.connect()
rows = session.execute("SELECT keyspace_name FROM system.schema_keyspaces")
if KEYSPACE in [row[0] for row in rows]:
log.info("dropping existing keyspace...")
session.execute("DROP KEYSPACE " + KEYSPACE)
log.info("creating keyspace...")
session.execute("""
CREATE KEYSPACE %s
WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '2' }
""" % KEYSPACE)
log.info("KEYSPACE")
session.set_keyspace(KEYSPACE)
log.info("TABLE:")
session.execute("""
CREATE TABLE mytable (
primkey text,
column1 text,
column2 timestamp,
PRIMARY KEY (primkey, column1)
)
""")
query = SimpleStatement("""
INSERT INTO mytable (primkey, column1, column2)
VALUES (%(key)s, %(a)s, %(b)s)
""", consistency_level=ConsistencyLevel.ONE)
prepared = session.prepare("""
INSERT INTO mytable (primkey, column1, column2)
VALUES (?, ?, ?)
""")
timestamp = int(time.time())
now = datetime.utcnow()
log.info("original time: %s", now)
session.execute(query, dict(key="simple", a='a', b=timestamp))
session.execute(prepared.bind(("prepared", 'a', timestamp)))
# insert using datetime
session.execute(query, dict(key="d_simple", a='a', b=now))
session.execute(prepared.bind(("d_prepared", 'a', now)))
future = session.execute_async("SELECT * FROM mytable")
log.info("key\t|\tcolumn1\t|\tcolumn2")
log.info("---\t----\t----")
try:
rows = future.result()
except Exception:
log.exception()
for row in rows:
log.info('\t'.join([str(c) for c in row]))
session.execute("DROP KEYSPACE " + KEYSPACE)
if __name__ == "__main__":
main()