Contents |
This tutorial will explain all the steps that you need to perform in order to connect to CUBRID Database and run SQL statements through Python programming language. You can use this API just like JDBC Driver in Java.
Even if the APIs are standard, in order to correctly connect to a certain DBMS (CUBRID, MySQL, Oracle, DB2, MS-SQL, PostgreSQL, etc) you have to use the right module created exactly for that particular database system. The latest version upon composing this tutorial was Python DB API 2.0.
CUBRID-Python is registered as an open source project at NAVER Development Center, and the source code is distributed in an open form, thus, it has to be manually compiled before usage. CUBRID-Python API is compatible with CUBRID 2008 R4.0 and newer, and Python 2.4 or later.
At any time if you feel lost somewhere, you can always visit the main page for Python Tutorial to start from the beginning. Or, if you have any troubles connecting to CUBRID through Python, post your questions to the Python Forum at http://www.cubrid.org/forum.
You can download Python Installer for Windows from the Official site http://python.org/download/. At this point you will see me using Python 2.7.
In fact, there is no need to install anything. You just have to copy the necessary files to the Lib folder of your Python installation.
Notes: CUBRID-Python driver depends on the CUBRID CCI(CUBRID C Interface) library. When you install CUBRID in "Prepareing CUBRID" step, the CCI library is automatically installed in %CUBRID%\bin. Otherwise, when you run your python scripts to access CUBRID DB, the below error will occur:
ImportError: DLL load failed: The specified module could not be found.
Most Linux distributions often come already bundled with Python 2.6.5. However, by default the Development Header Files are usually absent. So, considering that Python 2.6.5 is installed, let's install the Development Package, which is required to build all kinds of extensions, including CUBRID-Python Connector. If you have another version of Python such as 2.7.x you have to install python2.7-x and so on.
sudo apt-get install python2.6-dev
This Development Package is enough to build the Python Driver for CUBRID.
python setup.py build
sudo python setup.py install
| IMPORTANT! Before executing any example make sure you have Started the CUBRID Service and Started your Database. Otherwise, you will receive an error because your database is NOT started. |
In this example, we will use posts for a table name. The following is the Schema for it. Likewise, we will create a database called testdb, which will store the posts table. Finally, we will store some random data to this table.
CREATE TABLE posts( id integer, title varchar(255), body string, last_updated timestamp );
The following is the typical code used to execute the database query in CUBRID-Python API. We will use a simple query as an example to connect to the CUBRID Database.
| REMEMBER: Common mistake users often make when using Python 3.x is to try to print out using just print method. In Python 3.x it has been changed to print(), so put parenthesis after "print" like print('something') |
import CUBRIDdb con = CUBRIDdb.connect('CUBRID:localhost:33000:testdb:::', 'test_user', 'test_passwd') c = con.cursor() c.execute('select * from posts') rows = c.fetchall() for r in rows: print r # Python 3.x: put parenthesis after "print" like "print(r)" """ Below is a sample output retrieved from the "testdb" database. [1, 'aaa', '2006-11-2 23:53:0', 'hello, cubrid'] [2, 'bbb', '2006-11-3 0:14:0', 'good database system'] [3, 'ccc', '2006-11-15 0:5:23', 'happy python'] """ c.close() con.close()
The above example is quite straightforward. If simply explained, CUBRID-Python requires to import CUBRIDdb module to get started. According to Python API name conventions, the db postfix is appended after the module name CUBRID, thus forming CUBRIDdb.
After import-ing the necessary API, in our case CUBRID-Python API, we need to establish the database connection. Use CUBRIDdb's connect() function to establish the connection. For more info about the function see the syntax below. As shown in the above example, if username and password is omitted, the DEFAULT values (username: 'PUBLIC', password: - empty password) will be used. If the connection is successfully established, the Connection class instance will be returned.
con.cursor() call returns an object of the Cursor class. All database operations should be performed through the Cursor object. Cursor class has several methods such as execute() or fetchall(). The execute method is used to actually execute the SQL statements, while fetchall() retrieves all the results in tuple format. Each tuple represents a specific row in the database.
Python DB API is composed of connect() module class, Connection object, Cursor object, and many other auxiliary functions. For more information refer to Python DB API 2.0 Official Documentation.
Below are the documentation of the CUBRID-Python module functions necessary during the interaction with CUBRID database system.
As described in the above example, connect() function attempts to establish the connection with the database server by using connection information passed with a url string argument. If the HA feature is enabled in CUBRID, you must specify the connection information of the standby server, which is used for failover when failure occurs, in the url string argument of this function. If the user name and password is not given, then the "PUBLIC" connection will be made by default. Exclusive use of keyword parameters strongly recommended. Consult the CUBRID CCI documentation for more details.
cubriddb.connect(url, user, passwd)
Connection object maintains the connection with the database server, providing the instance methods such as cursor(), commit(), rollback(), and close().
cursor() method returns the object of the Cursor class, which can be used to retrieve the results of the recent query.
As the name of the function implies, the commit() method commits the latest changes to the database server.
rollback() function cancels the latest changes by rolling back the transaction.
close() method disconnects the connection with the database server.
Cursor class object is used to execute the queries and retrieve the results. As described above the Cursor object can be obtained by calling the cursor() method of the Connection class instance.
c = con.cursor() c.execute('select * from posts') row = c.fetchone() print row # Python 3.x: put parenthesis after "print" like "print(row)" # Output: {'body': 'hello, cubrid', 'created_at': '2006-11-2 23:53:0', 'id': 1, 'title': 'aaa'} print row['title'] # Python 3.x: put parenthesis after "print" like "print(row['title'])" # Output: aaa
Once you have received the Cursor object, you are ready to execute() the queries.
c.execute(SQL ,[, args],[,type])
c = con.cursor()
args = (4, 'ddd', 'CUBRID-Python is Open Source!!')
c.execute('insert into posts(id, title, body, created_at) values (?, ?, ?, SYSTIMESTAMP)', args)
con.commit()
c.execute('select * from posts')
rows = c.fetchall()
print rows
# Python 3.x: put parenthesis after "print" like "print(rows)"
#[[!1, 'aaa', '2006-11-2 23:53:0', 'hello, cubrid'], [2, 'bbb', '2006-11-3 0:14:0', 'good database system'], [3, 'ccc', '2006-11-15 0:5:23', 'happy python'], [4, 'ddd', '2006-11-30 22:54:9', 'CUBRID-Python is Open Source!!']]
If data type of args is tuple,it's mean driver will process the data as set,and type is data type of set's element.Default type is 'string'. The feature is support by version 9.1.0.0003 or later.
Example
con = CUBRIDdb.connect('CUBRID:10.34.64.218:30000:demodb:dba::')
c = con.cursor()
set_val=(('abc','def'),('1','23','48'))
etype = (FIELD_TYPE.CHAR,FIELD_TYPE.INT)
c.execute("CREATE TABLE set_tbl_char_int ( col_1 set(CHAR(5)),col_2 set(int));")
c.execute("insert into set_tbl_int VALUES(?,?)", set_val,etype)
con.commit();
c.close()
con.close()
This method can be used to retrieve one record at a time from the results set.
This method can be used to retrieve all the records that are in the results set.
This method can be used to retrieve the n number of records at a time from the results set.
c.fetchmany([n])
c = con.cursor() args = ('B') c.execute('select * from posts where id = ?', args) r = c.fetchone() print r # Python 3.x: put parenthesis after "print" like "print(r)" # Output: 'B', 'Bronze' c.execute('select * from posts where id > ?', args) print c.arraysize # Python 3.x: put parenthesis after "print" like "print(c.arraysize)" # Output: 1 r = c.fetchmany(3) print r # Python 3.x: put parenthesis after "print" like "print(r)" # Output: ['X', 'Mixed', 'W', 'Woman', 'M', 'Man']
If it is necessary to get the information about column properties of the obtained records, description method of the Cursor object should be called.
print c.description # Python 3.x: put parenthesis after "print" like "print(c.description)" # Output: (('s_name', 1, 0, 0, 1, 0, 0), ('f_name', 2, 0, 0, 6, 0, 0))
| Number | Data Type |
| 1 | CHAR |
| 2 | VARCHAR, string |
| 3 | NCHAR |
| 4 | VARNCHAR |
| 5 | BIT |
| 6 | VARBIT |
| 7 | NUMERIC |
| 8 | INT |
| 9 | SHORT |
| 10 | MONETARY |
| 11 | FLOAT |
| 12 | DOUBLE |
| 13 | DATE |
| 14 | TIME |
| 15 | TIMESTAMP |
| 19 | OBJECT |
| 32 | SET |
| 64 | MULTISET |
| 96 | SEQUENCE |