summaryrefslogtreecommitdiff
path: root/Db/sqlalchemy_example_code.py
blob: fc38b38b4bfc3feed5771bcea7ca684e2b1c43c0 (plain)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# coding: utf-8
import MySQLdb
import time, sys
USER = "asdfus"
PASSWORD = "gTYgT&M6q"
DATABASE = "asdfus"


from sqlalchemy import Column, Integer, LargeBinary, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql://{}:{}@localhost/{}'.format(USER, PASSWORD, DATABASE))
Session = sessionmaker(bind=engine)
session = Session()
connection = engine.connect()
#result = connection.execute("select username from users")
#for row in result:
#    print "username:", row['username']
#connection.close()


Base = declarative_base()
metadata = Base.metadata


class ImCmd(Base):
    __tablename__ = 'im_cmd'
    id = Column(Integer, primary_key=True)
    date = Column(Integer)
    remote_addr = Column(String(16))
    name = Column(String(16))
    url = Column(String(256))
    dir = Column(String(2))
    oldfile = Column(String(256))
    newfile = Column(String(256))
    cmd = Column(LargeBinary)
    dataobj = Column(LargeBinary)
    tag = Column(String(50))
#def __repr__(self):
#...        return "<User(name='%s', fullname='%s', password='%s')>" % (
#...                             self.name, self.fullname, self.password)


for instance in session.query(ImCmd).order_by(ImCmd.id): 
     print instance.name, instance.date


ed_user = User(name='ed', fullname='Ed Jones', password='edspassword')
session.add(ed_user)
#session.add_all([
#...     User(name='wendy', fullname='Wendy Williams', password='foobar'),
#...     User(name='mary', fullname='Mary Contrary', password='xxg527'),
#...     User(name='fred', fullname='Fred Flinstone', password='blah')])

#session.commit()

class Db(object):
        def __init__ (self):
                self.conn = None
                self.cursor = None
                self.connect()

        def connect (self):
                self.conn = MySQLdb.connect (host = "lalalizard.com",
                    user = USER,
                    passwd = PASSWORD,
                    db = DATABASE
                    )
                self.cursor = self.conn.cursor ()

        def execute (self,sql,args=()):
                try:
                        self.cursor.execute(sql,args)
                except MySQLdb.Error, e:
                        print "Error %d: %s" % (e.args[0], e.args[1])
                        # sys.exit (1)
                        self.connect()
                        self.cursor.execute(sql,args)

        def lastinsertid (self):
                return self.conn.insert_id()

        def insert_cmd (
            self, 
            date=time.time(), 
            remote_addr="NULL", 
            username="NULL", 
            url="NULL", 
            directory="NULL", 
            oldfile="NULL", 
            newfile="NULL", 
            cmd="NULL", 
            dataobj="NULL", 
            tag="NULL"):
            try:
                sql = "INSERT INTO im_cmd "
                sql += "(date, remote_addr, name, url, dir, oldfile, newfile, cmd, dataobj, tag) "
                sql += "VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
                #or "NULL"
                args = (date, remote_addr, username, url, directory, oldfile, newfile, cmd, dataobj, tag)
                #args = (now(), os.environ['REMOTE_ADDR'], name, url, dir, oldfile, newfile, " ".join(cmd),dataobj)
                self.execute(sql, args)
            except Exception as e:
                sys.stderr.write(str(e))
                return