def selectQuery(query, params): try: connect = Connector() connect = connect.connect() with connect: cursor = connect.cursor() cursor.execute(query, params) result = cursor.fetchall() cursor.close() connect.close() except MySQLdb.Error: raise MySQLdb.Error("select Error") return result
def ins_upd_delQuery(query, params): try: connect = Connector() connect = connect.connect() with connect: cursor = connect.cursor() connect.begin() cursor.execute(query, params) connect.commit() cursor.close() id = cursor.lastrowid connect.close() except MySQLdb.Error: raise MySQLdb.Error("Update error") return id
def create(date, thread, message, user, forum, opt): verify(table_name="Threads", param="id", val=thread) verify(table_name="Forums", param="short_name", val=forum) verify(table_name="Users", param="email", val=user) if len(selectQuery("SELECT Threads.id FROM Threads,Forums WHERE Threads.forum = Forums.short_name " "AND Threads.forum = %s AND Threads.id = %s", (forum, thread, ))) == 0: raise Exception("no thread with id = " + thread + " in forum " + forum) if "parent" in opt: if len(selectQuery("SELECT Posts.id FROM Posts, Threads WHERE Threads.id = Posts.thread " "AND Posts.id = %s AND Threads.id = %s", (opt["parent"], thread, ))) == 0: raise Exception("No post with id = " + opt["parent"]) query = "INSERT INTO Posts (message, user, forum, thread, date" values = "(%s, %s, %s, %s, %s" parameters = [message, user, forum, thread, date] for param in opt: query += ", "+param values += ", %s" parameters.append(opt[param]) query += ") VALUES " + values + ")" update_thread_posts = "UPDATE Threads SET posts = posts + 1 WHERE id = %s" con = Connector() con = con.connect() con.autocommit(False) with con: cursor = con.cursor() try: con.begin() cursor.execute(update_thread_posts, (thread, )) cursor.execute(query, parameters) con.commit() except Exception as e: con.rollback() raise Exception("Database error: " + e.message) #DatabaseConnection.connection.commit() post_id = cursor.lastrowid cursor.close() con.close() post = posts_query(post_id) del post["dislikes"] del post["likes"] del post["parent"] del post["points"] return post