Giter Site home page Giter Site logo

py2jdbc's Introduction

py2jdbc

py2jdbc is a Python module that accesses JDBC-compliant databases. It implements the Python Database API Specification 2.0 specification.

continuous integration build status documentation

Installation

pip install py2jdbc

This module currently uses ctypes for ffi access to the JNI API. Other branches will consider switching to Cython/Pyrex or writing pure C++ extensions.

Quick Start

conn = py2jdbc.onnect('jdbc:sqlite::memory:')
c = conn.cursor()
c.execute("""
    create table tests(
        id integer primary key,
        name text not null
    )
""")
c.execute("insert into tests(id, name) values (?, ?)", (1, 'Hello World'))
for row in c.execute("select * from test"):
    print(row)
c.close()
conn.close()

Or even:

with py2jdbc.connect('jdbc:sqlite::memory:') as conn:
    with conn.cursor() as c:
        c.execute("""
            create table tests(
                id integer primary key,
                name text not null
            )
        """)
        c.execute("insert into tests(id, name) values (?, ?)", (1, 'Hello World'))
        for row in c.execute("select * from test"):
            print(row)

Connect

Connect to your database with py2jdbc.connect by passing your JDBC URL. By default, your Java classpath will be loaded from any CLASSPATH environment variable, and any jar in a lib directory under your current working directory. You can also pass the CLASSPATH in the connection call:

py2jdbc.connect('jdbc:sqlite::memory:', classpath=['path1', 'path2'])

This returns the Connection object.

Execute

Bind variables use question marks, like JDBC, and can bind to sequences or generators:

# insert a row
c.execute("insert into tests(id, name) values (?, ?)", (1, "Hello World"))

# insert 10 rows
c.executemany("insert into tests(id, name) values (?, ?)",
    (i + 1, 'testing')
    for i in range(10)
)

Select

Selecting from a database will automatically describe the result set and try to convert values to standard Python types:

c.execute("select * from test")
for row in c:
    print(row)  # -> [1, 'Hello World']

py2jdbc's People

Contributors

swstephe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

py2jdbc's Issues

demical datatype error

When i select decimal data from table,i get this erro:java.sql.SQLException: Value is not a number: java.lang.String.
…… File "D:\tools\Anaconda3\lib\site-packages\py2jdbc\dbi.py", line 149, in get value = rs.getDouble(i) File "D:\tools\Anaconda3\lib\site-packages\py2jdbc\sql.py", line 875, in <lambda> self.getDouble = lambda i, o=obj: cls.getDouble(o, i) File "D:\tools\Anaconda3\lib\site-packages\py2jdbc\wrap.py", line 199, in __call__ raise self.cls.env.exception(e) py2jdbc.sql.Instance: java.sql.SQLException: Value is not a number: java.lang.String
One solution is use cast in sql.
Another is use java.math.BigDecimal instead of Double to get the value.
I hope it was helpful.

Is the library OS independent?

Makes me wonder if anybody could successfully run the library on Windows or macOS?

On Windows, I get the error

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    import py2jdbc
  File "C:\Users\robert\AppData\Local\Programs\Python\Python37\lib\site-packages\py2jdbc\__init__.py", line 2, in <module>
    from py2jdbc.dbi import (
  File "C:\Users\robert\AppData\Local\Programs\Python\Python37\lib\site-packages\py2jdbc\dbi.py", line 6, in <module>
    from py2jdbc.wrap import get_env
  File "C:\Users\robert\AppData\Local\Programs\Python\Python37\lib\site-packages\py2jdbc\wrap.py", line 4, in <module>
    import py2jdbc.jni
  File "C:\Users\robert\AppData\Local\Programs\Python\Python37\lib\site-packages\py2jdbc\jni.py", line 2765, in <module>
    signal.signal(signal.SIGHUP, signal_handler)
AttributeError: module 'signal' has no attribute 'SIGHUP'

which is right, because Windows does not know SIGHUP.

Om macOS I get the error

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    import py2jdbc
  File "/usr/local/lib/python3.7/site-packages/py2jdbc/__init__.py", line 2, in <module>
    from py2jdbc.dbi import (
  File "/usr/local/lib/python3.7/site-packages/py2jdbc/dbi.py", line 6, in <module>
    from py2jdbc.wrap import get_env
  File "/usr/local/lib/python3.7/site-packages/py2jdbc/wrap.py", line 4, in <module>
    import py2jdbc.jni
  File "/usr/local/lib/python3.7/site-packages/py2jdbc/jni.py", line 2620, in <module>
    libjvm.JNI_GetDefaultJavaVMInitArgs.retval = jint
  File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ctypes/__init__.py", line 377, in __getattr__
    func = self.__getitem__(name)
  File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ctypes/__init__.py", line 382, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: dlsym(RTLD_DEFAULT, JNI_GetDefaultJavaVMInitArgs): symbol not found

I checked the libjvm.dylib and the symbol is there.

Any idea?

about connect

i was install py2jdbc in python ]
and i was try connect a single sqlite database

but it show this error message

OSError: [WinError 193] %1 não é um aplicativo Win32 válido

the complite trace was there

PS C:\Users\xxx\Documents> & C:/Users/xxx/AppData/Local/Programs/Python/Python39/python.exe c:/Users/xxx/Documents/p01/novo.py
Traceback (most recent call last):
File "c:\Users\xxx\Documents\p01\novo.py", line 1, in
import py2jdbc
File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\py2jdbc_init_.py", line 2, in
from py2jdbc.dbi import (
File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\py2jdbc\dbi.py", line 6, in
from py2jdbc.wrap import get_env
File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\py2jdbc\wrap.py", line 4, in
import py2jdbc.jni
File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\py2jdbc\jni.py", line 2619, in
libjvm = CDLL(find_libjvm())
File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\ctypes_init_.py", line 374, in init
self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1 não é um aplicativo Win32 válido

please you can help me about whats happen
i using vs code and windows 10

thanks

Thread safe?

Hello,

I was wondering can this be used safely with multi-threading?
I've tried using JayDeBeAPI in a multithreaded scenario but it seems like JPype1 produces a seg-fault.

Thanks!

Cannot have 2 instances of py2JDBC to connect to 2 databases at the same time

Hi,

We have a use case to connect to 2 databases at the same time (technically in same file), but it seems py2jdbc allows us to have just one connection and second connection fails.

for instance

import py2jdbc

conn1 = py2jdbc.connect(host1, uname1, password1, classpath=jar_path1)
it goes through but if we want to have
conn2 = py2jdbc.connect(host2, uname2, password2, classpath=jar_path2)
it throws error
No suitable driver found for host2.

Please advise how we can have 2 connections with py2jdbc

Thanks

Consider using the mutf8 package

I've recently added a C extension for my 8-year old mutf8 decoder/encoder from Jawa that speed things up quite a bit. As part of that, I've extracted it into its own https://github.com/TkTech/mutf8 extension. On large strings the performance difference is typically 20x - 40x the pure-python decoder/encoder.

Thank you for py2jdbc! While getting it ready for release I was trying to find test data and stumbled on your mutf8 tests, which are now used in the mutf8 package.

Flaky test

tests/test_dbi.py can fail when executing with pytest --randomly-seed=123.

Use a Windows alternative to signals on Windows.

Traceback (most recent call last):
File "test.py", line 3, in
import py2jdbc
File "C:\Users\robert\AppData\Local\Programs\Python\Python37\lib\site-packages\py2jdbc_init_.py", line 2, in
from py2jdbc.dbi import (
File "C:\Users\robert\AppData\Local\Programs\Python\Python37\lib\site-packages\py2jdbc\dbi.py", line 6, in
from py2jdbc.wrap import get_env
File "C:\Users\robert\AppData\Local\Programs\Python\Python37\lib\site-packages\py2jdbc\wrap.py", line 4, in
import py2jdbc.jni
File "C:\Users\robert\AppData\Local\Programs\Python\Python37\lib\site-packages\py2jdbc\jni.py", line 2765, in
signal.signal(signal.SIGHUP, signal_handler)
AttributeError: module 'signal' has no attribute 'SIGHUP'

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.