Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 21-30 of 116 total

Storm ORM by Canonical in WSGI enabled applications

#!/usr/bin/env python
# vim:ts=4:sw=4:et
# (c) 2007 Vsevolod Balashov <vsevolod@balashov.name> under terms of LGPL 2.1
# use Storm ORM <https://storm.canonical.com> in WSGI enabled applications

"""WSGI middleware for Storm.

This is the database access inteface for WSGI enabled (PEP 333) web applications.

Pylons framework example:

in wsgiapp.py

from storm.database import create_database
from middlestorm import MiddleStorm
...

# CUSTOM MIDDLEWARE HERE
app = MiddleStorm(app, create_database(config['app_conf']['sqlalchemy.default.uri']))

in controller:

class DemoController(BaseController):
    def index(self):
        store = request.environ['storm.store']
        ...
"""

from storm.database import Database
from storm.store import Store
from threading import local

__all__ = ["MiddleStorm"]
__author__ = "Vsevolod Balashov <http://vsevolod.balashov.name>"
__version__ = "0.1"

class SingleConn(Database):
    """Database proxy class.
    Share single database connection between all Store object instances in threads.
    If you have readonly database or not use transactions why not?
    """
    def __init__(self, database):
        self._database = database
        self._connection = database.connect()
    def connect(self):
        return self._connection

class MiddleStorm(object):
    """WSGI middleware.
    Add Store object instance in environ['storm.store']. Each thread contains own instance.
    """

    def __init__(self, app, database, single = False):
        """Create WSGI middleware.
        @param app: up level application or middleware.
        @param database: instance of Database returned create_database.
        @param: single: use single database connection in all threads. 
        """
        assert isinstance(database, Database), \
            'database must be subclass of storm.database.Database'
        if single:
            self._database = SingleConn(database)
        else:
            self._database = database
        self._app = app
        self._local = local()

    def __call__(self, environ, start_response):
        try:
            environ['storm.store']  = self._local.store
        except AttributeError:
            environ['storm.store']  = \
                self._local.__dict__.setdefault('store', Store(self._database))
        return self._app(environ, start_response)

PHP : Conectar con Access / Connect with Access

Conectar con Access / Connect with Access.
Código fuente / Source code :

$pathDB = str_replace("/", "\\", $_SERVER["DOCUMENT_ROOT"]) . "\\directory1\\directory2\\bdd.mdb";

if(!file_exists($pathDB))
{
echo "!!! Base de datos no encontrada ".$pathDB;
exit;
}

$conexion = odbc_connect("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".$pathDB, "ADODB.Connection", "", "SQL_CUR_USE_ODBC");
$sql="select * from tabla where 1";
$resultado=odbc_exec($conexion,$sql);
if($resultado)
{
	while($fila=odbc_fetch_array($resultado))
	{
	echo $fila['campo1']."<br />";
	echo $fila['campo2']."<br />";
	}
odbc_close_all();
}

SQL Server: Search through stored procedures for code

This returns the names of stored procedures that contain the text you're looking for.

select so.name as 'storProc'
from sysobjects so
join syscomments sc
on so.id=sc.id
where so.type='P'
and sc.[text] like '%BIT_YOU_WANT_TO_FIND%' 


Say for example you're looking for all the stored procedures that mentioned the table 'user_table' - then just use this script and the all the stored procedures that make mention of this will be returned.

SQL: Check For Duplicate Rows

SELECT email,
COUNT(email) AS NumOccurrences
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )

C#: Execute A Query & Return A Reader

public static SqlDataReader GetReader(string Query)
{
	string ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["CONNECTION_STRING_NAME"].ConnectionString;
	SqlConnection con = new SqlConnection(ConnectionString);
	SqlCommand command = new SqlCommand();

	command.Connection = con;
	command.Connection.Open();
	command.CommandText = Query;
	return command.ExecuteReader();
}

SQL: Copy Data From One Table Into Another

// SQL Query to copy data from one table and insert it into another

INSERT INTO TABLE2 (COL1, COL2, COL3) SELECT COL1, COL4, COL7 FROM TABLE1

dbms database class

I'm at my first attempt at creating something for the PyS60 and I needed a simple sql wrapper class...
I'm an experienced programmer, but has never programmed in python for s60 and it's been a while since I've used Python... So I hope this will help somebody, not annoy ;-)

# Filename: db.py save in your Python dir
import e32db

class db:
    def __init__(self, dbpath):
	self.db = e32db.Dbms()
	self.dbv = e32db.Db_view()
	self.reset_counters()
	try:
	    self.db.open(unicode(dbpath))
	except:
	    self.db.create(unicode(dbpath))
	    self.db.open(unicode(dbpath))

    def reset_counters(self):
	self.affected_rows = 0
	self.num_rows = 0
	self.__internal_counter = 0

    def query(self, sql):
	self.reset_counters()
	if sql.lower().startswith('select'):
	    self.dbv.prepare(self.db, unicode(sql))
	    self.dbv.first_line()
	    self.num_rows = self.dbv.count_line()
	else:
	    self.affected_rows = self.db.execute(unicode(sql))

    def next(self):
	row = {'id': 0}
	if self.num_rows < 1:
	    self.reset_counters()
	    raise StopIteration
	elif self.__internal_counter < self.num_rows:
	    self.dbv.get_line()
	    for i in range(self.dbv.col_count()):
		row[i] = self.dbv.col(i+1)
	    self.dbv.next_line()
	    self.__internal_counter += 1
	    return row
	else:
	    self.reset_counters()
	    raise StopIteration

    def __iter__(self):
	return self


Now to create and fill db, create a file in the same dir as the db.py with this content:
# Change __exec_path to the path of your python script dir
__exec_path = "E:\\Python\\"
dbname = "test"

import sys
sys.path.append(__exec_path)
from db import db

# This will open E:\\Python\test.db - it will be created first, if not existing
mydb = db(__exec_path+dbname+'.db')
mydb.query("create table testing (id counter, name varchar)")
mydb.query("insert into testing (name) values ('test 1')")
mydb.query("insert into testing (name) values ('test 2')")



Now go ahead and have fun:
# Again change __exec_path to the path of your python script dir
__exec_path = "E:\\Python\\"
dbname = "test"

import sys
sys.path.append(__exec_path)
from db import db

# Opens E:\\Python\test.db
mydb = db(__exec_path+dbname+'.db')
mydb.query("select * from testing")
for row in mydb:
    print "-> ",row[0]," ",row[1]," <-"


Have fun!
Dan

SQL 2005 TSQL Script to list tables, indexes, file groups along with file names

// description of your code here

select 'table_name'=object_name(i.id)  ,i.indid
,'index_name'=i.name  ,i.groupid
,'filegroup'=f.name  ,'file_name'=d.physical_name
,'dataspace'=s.name from sys.sysindexes i
,sys.filegroups f  ,sys.database_files d
,sys.data_spaces s
where objectproperty(i.id,'IsUserTable') = 1
and f.data_space_id = i.groupid
and f.data_space_id = d.data_space_id
and f.data_space_id = s.data_space_id
order by f.name,object_name(i.id),groupid
go

PRNG In SQL Select

Simple example of a PRNG (pseudo-random number generator) written into a SQL statement

Example is in T-SQL, but it ports well

Actual application should use either a better random algorithm, or the output be used with randomized seeds. This is definitely not cryptographically secure. It's very handy if you need a simple random number with your recordset though.

-- Setup some vars we'll need
DECLARE @prng TABLE (seed BIGINT, rnum nchar(10))
DECLARE @seeds TABLE (seed BIGINT)
DECLARE @seed BIGINT
DECLARE @C1 BIGINT, @C2 BIGINT, @C3 BIGINT
SET @seed = 0
SET @C1 = 1664525
SET @C2 = 4294967296
SET @C3 = 1013904223

-- Create a seed table so we can have some data to use
WHILE @seed < 10
BEGIN
    INSERT INTO @seeds (seed) VALUES (@seed)
    SET @seed = @seed + 1
END

-- Create our PRNG (inserts into table for illustrative purposes)
-- prng(seed) ::= ((((C1 * seed) % C2) + C3) % C2) / C2
-- Then convert prng(seed) into a string
-- of 10 chars, 8 of which are decimal places
INSERT INTO @prng
SELECT
    seed,
    REPLACE(
        STR(
            ( CAST((((@C1*seed)%@C2)+@C3)%@C2 AS FLOAT) )
            / ( CAST(@C2 AS FLOAT)),
            10, 8
        ),
        ' ', '0') AS rnum
FROM @seeds

-- Let's take a look at what we created
SELECT * FROM @prng

SQL Transaction in Rails

def fetch_value
	sql = ActiveRecord::Base.connection();
	sql.execute "SET autocommit=0";
	sql.begin_db_transaction
	id, value =
	sql.execute("SELECT id, value FROM sometable WHERE used=0 LIMIT 1 FOR UPDATE").fetch_row;
	sql.update "UPDATE sometable SET used=1 WHERE id=#{id}";
	sql.commit_db_transaction
 
	value;
end
« Newer Snippets
Older Snippets »
Showing 21-30 of 116 total