Git Product home page Git Product logo

simplemysql's Introduction

#SimpleMysql An ultra simple wrapper for Python MySQLdb with very basic functionality

Installation

With pip or easy_install

pip install simplemysql or easy_install simplemysql

Or from the source

python setup.py install

Usage

For normal connection

from simplemysql import SimpleMysql

db = SimpleMysql(
	host="127.0.0.1",
	db="mydatabase",
	user="username",
	passwd="password",
	keep_alive=True # try and reconnect timedout mysql connections?
)

For SSL Connection

from simplemysql import SimpleMysql

db = SimpleMysql(
    host="127.0.0.1",
    db="mydatabase",
    user="username",
    passwd="password",
    ssl = {'cert': 'client-cert.pem', 'key': 'client-key.pem'},
    keep_alive=True # try and reconnect timedout mysql connections?
)
# insert a record to the <em>books</em> table
db.insert("books", {"type": "paperback", "name": "Time Machine", "price": 5.55, year: "1997"})

book = db.getOne("books", ["name"], ["year = 1997"])

print "The book's name is " + book.name

Query methods

insert(), update(), delete(), getOne(), getAll(), lastId(), query()

insert(table, record{})

Inserts a single record into a table.

db.insert("food", {"type": "fruit", "name": "Apple", "color": "red"})
db.insert("books", {"type": "paperback", "name": "Time Machine", "price": 5.55})

update(table, row{}, condition[])

Update one more or rows based on a condition (or no condition).

# update all rows
db.update("books", {"discount": 0})

# update rows based on a simple hardcoded condition
db.update("books",
	{"discount": 10},
	["id=1"]
)

# update rows based on a parametrized condition
db.update("books",
	{"discount": 10},
	("id=%s AND year=%s", [id, year])
)

insertBatch(table, rows{})

Insert Multiple values into table.

# insert multiple values in table
db.insertBatch("books", [{"discount": 0},{"discount":1},{"discount":3}])

insertOrUpdate(table, row{}, key)

Insert a new row, or update if there is a primary key conflict.

# insert a book with id 123. if it already exists, update values
db.insertOrUpdate("books",
		{"id": 123, type": "paperback", "name": "Time Machine", "price": 5.55},
		"id"
)

getOne(table, fields[], where[], order[], limit[])

getAll(table, fields[], where[], order[], limit[])

Get a single record or multiple records from a table given a condition (or no condition). The resultant rows are returned as namedtuples. getOne() returns a single namedtuple, and getAll() returns a list of namedtuples.

book = db.getOne("books", ["id", "name"])
# get a row based on a simple hardcoded condition
book = db.getOne("books", ["name", "year"], ("id=1"))
# get multiple rows based on a parametrized condition
books = db.getAll("books",
	["id", "name"],
	("year > %s and price < %s", [year, 12.99])
)
# get multiple rows based on a parametrized condition with an order and limit specified
books = db.getAll("books",
	["id", "name", "year"],
	("year > %s and price < %s", [year, 12.99]),
	["year", "DESC"],	# ORDER BY year DESC
	[0, 10]			# LIMIT 0, 10
)

lastId()

Get the last insert id

# get the last insert ID
db.lastId()

lastQuery()

Get the last query executed

# get the SQL of the last executed query
db.lastQuery()

delete(table, fields[], condition[], order[], limit[])

Delete one or more records based on a condition (or no condition)

# delete all rows
db.delete("books")

# delete rows based on a condition
db.delete("books", ("price > %s AND year < %s", [25, 1999]))

query(table)

Run a raw SQL query. The MySQLdb cursor is returned.

# run a raw SQL query
db.query("DELETE FROM books WHERE year > 2005")

commit()

Insert, update, and delete operations on transactional databases such as innoDB need to be committed

# Commit all pending transaction queries
db.commit()

simplemysql's People

Contributors

apogre avatar gdmachado avatar knadh avatar milosb793 avatar ptrcarta avatar subhashdasyam avatar zetaphor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simplemysql's Issues

Disabling and re-enabling autocommit on the fly

Hi,

I want to start a connection with autocommit enabled (autocommit=True, which is fine for most of the operations) and occasionally I want to disable it, run a transaction and then re-enable it.

To do so, I've done as follows:

  1. start the connection with autocommit enabled
db = SimpleMysql(
        host="127.0.0.1",
	db="mydatabase",
	user="username",
	passwd="password",
	keep_alive=True,
        autocommit = True
)
  1. disable autocommit when needed
cursor = db.query("SET autocommit = 0")
  1. run a bunch of queries, for instance
db.update(...)
db.insert(...)
db.delete(...)
  1. call commit
db.commit()
  1. finally, turn autocommit back on
cursor = db.query("SET autocommit = 1")

Is that safe or do you think it may cause issues during the connection?

Thanks

Last inserted id

Provide a method to get the last inserted id. E.g.
db.lastid(): return self.cursor.lastrowid

Or change the return value of db.insert.

SQL Injection

The code is vulnerable to SQL injection.

See, for example, line 153:
This is vulnerable to SQL injection.

Install Error: Missing ConfigParser

Was trying to install simplemysql (using pip3) and got an error saying that I was missing "ConfigParser". It seems that the package was renamed "configparser" (lowercase) to comply with PEP8.

incompatible with python 2.6.6

Python 2.6.6 (r266:84292, Sep 11 2012, 08:34:23)
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

from simplemysql import SimpleMysql
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.6/site-packages/simplemysql/init.py", line 1, in
from .simplemysql import SimpleMysql
File "/usr/lib/python2.6/site-packages/simplemysql/simplemysql.py", line 162
data = {k: data[k] for k in data if k not in keys}
^
SyntaxError: invalid syntax

Will simplimysql support Python 3.x?

Hello!
I want to upgrade my Python version to latest for using latest language features, but when I tried to install simplemysql, I occured an error

2018-03-10 13 18 57

And how described here, MySQL-python does not currently support Python 3.

Wrong limit parameter for _select method

Hello.

First of all, thanks for nice wrapper around MySQL.

But I'n not sure I fallow one part of code. Please correct me if I'm wrong.

Method _select line 229:

def _select(self, table=None, fields=(), where=None, order=None, limit=None):
........
#limit
if limit:
    sql += " LIMIT %s" % limit[0]
    if 1 in LIMIT:
        sql+= ", " + limit[1]

form my understanding this part should have look something like this:

# limit
if limit:
    sql += " LIMIT %s" % limit[0]
    if len(limit) > 1:
        sql = "%s, %s"% (sql, limit[1])

Best Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.