Chinaunix首页 | 论坛 | 认证专区 | 博客 登录 | 注册

漂泊的程序人生playmud.blog.chinaunix.net

云飞扬的blog----春天的布拉格 blog.playmud.org

  • 博客访问: 15127168
  • 博文数量: 121
  • 博客积分: 11195
  • 博客等级: 上将
  • 技术积分: 1984
  • 用 户 组: 普通用户
  • 注册时间: 2005-06-20 11:04
文章分类

全部博文(121)

文章存档

2013年(3)

2012年(34)

2011年(7)

2010年(11)

2009年(6)

2007年(7)

2006年(23)

2005年(30)

微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
sql relay的c++接口 2005-06-20 12:38:59

分类: C/C++

sql relay的c++接口


Programming with SQL Relay using the C++ API

Compiling an SQL Relay Client Program

When writing an SQL Relay client program using the C++ API, you need to include the sqlrclient.h file.

#include 

You'll also need to link against the sqlrclient and rudiments libraries. The include file is usually found in /usr/local/firstworks/include and the libraries are usually found in /usr/local/firstworks/lib.

The command to compile your .C file to object code will look something like this (assuming you're using GNU C++):

g++ -I/usr/local/firstworks/include -c myprogram.C

The command to compile your .o file to an executable will look something like this (assuming you're using GNU C++):

g++ -o myprogram myprogram.o -L/usr/local/firstworks/lib -lsqlrclient -lrudiments
Establishing a Session

To use SQL Relay, you have to identify the connection that you intend to use.

#include 

main() {

       sqlrconnection      con=new sqlrconnection("host",9000,"","user","password",0,1);

       ... execute some queries ...

       delete con;
}

After calling the constructor, a session is established when the first query, ping() or identify() is run.

For the duration of the session, the client stays connected to a database connection daemon. While one client is connected, no other client can connect. Care should be taken to minimize the length of a session.

If you're using a transactional database, ending a session has a catch. Database connection daemons can be configured to send either a commit or rollback at the end of a session if DML queries were executed during the session with no commit or rollback. Program accordingly.

Executing Queries

Allocate a cursor, then call sendQuery() or sendFileQuery() to run a query. The same cursor may be used over and over.

#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        cur->sendQuery("select * from my_table");

        ... do some stuff that takes a short time ...

        cur->sendFileQuery("/usr/local/myprogram/sql","myquery.sql");
        con->endSession();

        ... do some stuff that takes a long time ...

        cur->sendQuery("select * from my_other_table");
        con->endSession();

        ... process the result set ...

        delete cur;
        delete con;
}

Note the call to endSession() after the call to sendFileQuery(). Since the program does some stuff that takes a long time between that query and the next, ending the session there allows another client an opportunity to use that database connection while your client is busy. The next call to sendQuery() establishes another session. Since the program does some stuff that takes a short time between the first two queries, it's OK to leave the session open between them.

Commits and Rollbacks

If you need to execute a commit or rollback, you should use the commit() and rollback() methods of the sqlrconnection class rather than sending a "commit" or "rollback" query. There are two reasons for this. First, it's much more efficient to call the methods. Second, if you're writing code that can run on transactional or non-transactional databases, some non-transactional databases will throw errors if they receive a "commit" or "rollback" query, but by calling the commit() and rollback() methods you instruct the database connection daemon to call the commit and rollback API methods for that database rather than issuing them as queries. If the API's have no commit or rollback methods, the calls do nothing and the database throws no error. This is especially important when using SQL Relay with ODBC.

You can also turn Autocommit on or off with the autoCommitOn() and autoCommitOff() methods of the sqlrconnection class. When Autocommit is on, the database performs a commit after each successful DML or DDL query. When Autocommit is off, the database commits when the client instructs it to, or (by default) when a client disconnects. For databases that don't support Autocommit, autoCommitOn() and autoCommitOff() have no effect.

Temporary Tables

Some databases support temporary tables. That is, tables which are automatically dropped or truncated when an application closes it's connection to the database or when a transaction is committed or rolled back.

For databases which drop or truncate tables when a transaction is committed or rolled back, temporary tables work naturally.

However, for databases which drop or truncate tables when an application closes it's connection to the database, there is an issue. Since SQL Relay maintains persistent database connections, when an application disconnects from SQL Relay, the connection between SQL Relay and the database remains, so the database does not know to drop or truncate the table. To remedy this situation, SQL Relay parses each query to see if it created a temporary table, keeps a list of temporary tables and drops (or truncates them) when the application disconnects from SQL Relay. Since each database has slightly different syntax for creating a temporary table, SQL Relay parses each query according to the rules for that database.

In effect, temporary tables should work when an application connects to SQL Relay in the same manner that they would work if the application connected directly to the database.

Catching Errors

If your call to sendQuery() or sendFileQuery() returns a 0, the query failed. You can find out why by calling errorMessage().

#include 
#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        if (!cur->sendQuery("select * from my_nonexistant_table")) {
                cout << cur->errorMessage() << endl;
        }

        delete cur;
        delete con;
}

Substitution and Bind Variables

Programs rarely execute fixed queries. More often than not, some part of the query is dynamically generated. It's convenient to store queries in files so they can be changed by a non-C++ programmer. The SQL Relay API provides methods for making substitutions and binds in those queries.

For a detailed discussion of substitutions and binds, see this document.

Rather than just calling sendFileQuery() you call prepareFileQuery(), substitution(), inputBind() and executeQuery().

/usr/local/myprogram/sql/myquery.sql:

	select * from mytable $(whereclause)
Program code:
#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        cur->prepareFileQuery("/usr/local/myprogram/sql","myquery.sql");
        cur->substitution("whereclause","where col1=:value1");
        cur->inputBind("value1","true");
        cur->executeQuery();

        ... process the result set ...

        delete cur;
        delete con;
}

If you're using a database with an embedded procedural language, you may want to retrieve data from a call to one of it's functions. To facilitate this, SQL Relay provides the defineOutputBind() and getOutputBind() methods.

PL/SQL Procedure:
FUNCTION sp_mytable RETURN types.cursorType
l_cursor types.cursorType;
BEGIN
        OPEN l_cursor FOR SELECT * FROM mytable;
        RETURN l_cursor;
END;

Program code:
#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        cur->prepareQuery("begin  :result:=addTwoNumbers(:num1,:num2);  end;");
        cur->inputBind("num1",10);
        cur->inputBind("num2",20);
        cur->defineOutputBind("result",100);
        cur->executeQuery();
        int     result=atoi(cur->getOutputBind("result"));
        con->endSession();

        ... do something with the result ...

        delete cur;
        delete con;
}

The getOutputBind() method returns a NULL value as an empty string. If you would it to come back as a NULL instead, you can call the getNullsAsNulls() method. To revert to the default behavior, you can call getNullsAsEmptyStrings().

The getOutputBind() method returns a string, if you would like to get the value as a long or double, you can use getOutputBindAsLong() or getOutputBindAsDouble().

If you are using Oracle 8i or higher, you can insert data into BLOB and CLOB columns using the inputBindBlob(), inputBindClob() methods.

If you are curious how many bind variables have been declared in a query, you can call countBindVariables() after preparing the query.

#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        cur->executeQuery("create table images (image blob, description clob)");

        unsigned char   imagedata[40000];
        unsigned long   imagelength;

        ... read an image from a file into imagedata and the length of the
                file into imagelength ...

        unsigned char   description[40000];
        unsigned long   desclength;

        ... read a description from a file into description and the length of
                the file into desclength ...

        cur->prepareQuery("insert into images values (:image,:desc)");
        cur->inputBindBlob("image",imagedata,imagelength);
        cur->inputBindClob("desc",description,desclength);
        cur->executeQuery();

        delete cur;
        delete con;
}

Likewise, with Oracle 8i, you can retreive BLOB or CLOB data using defineOutputBindBlob(), defineOutputBindClob(), getOutputBind() and getOutputBindLength().

#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        cur->prepareQuery("begin  select image into :image from images;  select description into :desc from images;  end;");
        cur->defineOutputBindBlob("image");
        cur->defineOutputBindClob("desc");
        cur->executeQuery();

        char    *image=cur->getOutputBind("image");
        long    imagelength=cur->getOutputBindLength("image");

        char    *desc=cur->getOutputBind("desc");
        char    *desclength=cur->getOutputBindLength("desc");

        con->endSession();

        ... do something with image and desc ...

        delete cur;
        delete con;
}

Sometimes it's convenient to bind a bunch of variables that may or may not actually be in the query. For example, if you are building a web based application, it may be easy to just bind all the form variables/values from the previous page, even though some of them don't appear in the query. Databases usually generate errors in this case. Calling validateBinds() just prior to calling executeQuery() causes the API to check the query for each bind variable before actually binding it, preventing those kinds of errors. There is a performance cost associated with calling validateBinds().

Re-Binding and Re-Execution

Another feature of the prepare/bind/execute paradigm is the ability to prepare, bind and execute a query once, then re-bind and re-execute the query over and over without re-preparing it. If your backend database natively supports this paradigm, you can reap a substantial performance improvement.

#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        cur->prepareQuery("select * from mytable where mycolumn>:value");
        cur->inputBind("value",1);
        cur->executeQuery();

        ... process the result set ...

        cur->clearBinds();
        cur->inputBind("value",5);
        cur->executeQuery();

        ... process the result set ...

        cur->clearBinds();
        cur->inputBind("value",10);
        cur->executeQuery();

        ... process the result set ...

        delete cur;
        delete con;
}
Accessing Fields in the Result Set

The rowCount(), colCount() and getField() methods are useful for processing result sets.

#include 
#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        cur->sendQuery("select * from my_table");
        con->endSession();

        for (int row=0; rowrowCount(); row++) {
                for (int col=0; colcolCount(); col++) {
                        cout << cur->getField(row,col) << ",";
                }
                cout << endl;
        }

        delete cur;
        delete con;
}

The getField() method returns a string. If you would like to get a field as a long or double, you can use getFieldAsLong() and getFieldAsDouble().

You can also use getRow() which returns a NULL-terminated array of the fields in the row.

#include 
#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        cur->sendQuery("select * from my_table");
        con->endSession();

        for (int row=0; rowrowCount(); row++) {
                char    **rowarray=cur->getRow(row);
                for (int col=0; colcolCount(); col++) {
                        cout << rowarray[col] << ",";
                }
                cout << endl;
        }

        delete cur;
        delete con;
}

The getField() and getRow() methods return NULL fields as empty strings. If you would like them to come back as NULL's instead, you can call the getNullsAsNulls() method. To revert to the default behavior, you can call getNullsAsEmptyStrings().

If you want to access the result set, but don't care about the column information (column names, types or sizes) and don't mind getting fields by their numeric index instead of by name, you can call the dontGetColumnInfo() method prior to executing your query. This can result in a performance improvement, especially when many queries with small result sets are executed in rapid succession. You can call getColumnInfo() again later to turn off this feature.

Dealing With Large Result Sets

SQL Relay normally buffers the entire result set. This can speed things up at the cost of memory. With large enough result sets, it makes sense to buffer the result set in chunks instead of all at once.

Use setResultSetBufferSize() to set the number of rows to buffer at a time. Calls to getRow() and getField() cause the chunk containing the requested field to be fetched. Rows in that chunk are accessible but rows before it are not.

For example, if you setResultSetBufferSize(5) and execute a query that returns 20 rows, rows 0-4 are available at once, then rows 5-9, then 10-14, then 15-19. When rows 5-9 are available, getField(0,0) will return NULL and getField(11,0) will cause rows 10-14 to be fetched and return the requested value.

When buffering the result set in chunks, don't end the session until after you're done with the result set.

If you call setResultSetBufferSize() and forget what you set it to, you can always call getResultSetBufferSize().

When buffering a result set in chunks, the rowCount() method returns the number of rows returned so far. The firstRowIndex() method returns the index of the first row of the currently buffered chunk.

#include 
#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        cur->setResultSetBufferSize(5);

        cur->sendQuery("select * from my_table");

        int     done=0;
        int     row=0;
        char    *field;
        while (!done) {
                for (int col=0; colcolCount(); col++) {
                        if (field=cur->getField(row,col)) {
                                cout << field << ",";
                        } else {
                                done=1;
                        }
                }
                cout << endl;
                row++;
        }

        cur->sendQuery("select * from my_other_table");

        ... process this query's result set in chunks also ...

        cur->setResultSetBufferSize(0);

        cur->sendQuery("select * from my_third_table");

        ... process this query's result set all at once ...

        con->endSession();

        delete cur;
        delete con;
}
Cursors

Cursors make it possible to execute queries while processing the result set of another query. You can select rows from a table in one query, then iterate through it's result set, inserting rows into another table, using only 1 database connection for both operations.

For example:

#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cursor1=new sqlrcursor(con);
        sqlrcursor          *cursor2=new sqlrcursor(con);

        cursor1->setResultSetBufferSize(10);
        cursor1->sendQuery("select * from my_huge_table");

        int     index=0;
        while (!cursor1->endOfResultSet()) {
                cursor2->prepareQuery("insert into my_other_table values (:1,:2,:3)");
                cursor2->inputBind("1",cursor1->getField(index,1));
                cursor2->inputBind("2",cursor1->getField(index,2));
                cursor2->inputBind("3",cursor1->getField(index,3));
                cursor2->executeQuery();
        }

        delete cursor2;
        delete cursor1;
        delete con;
}

Prior to SQL Relay version 0.25, you would have had to buffer the first result set or use 2 database connections instead of just 1.

If you are using stored procedures with Oracle 8i or higher, a stored procedure can execute a query and return a cursor. A cursor bind variable can then retrieve that cursor. Your program can retrieve the result set from the cursor. All of this can be accomplished using defineOutputBindCursor(), getOutputBindCursor() and fetchFromOutputBindCursor().

PL/SQL Procedure:
FUNCTION sp_mytable RETURN types.cursorType
l_cursor types.cursorType;
BEGIN
        OPEN l_cursor FOR SELECT * FROM mytable;
        RETURN l_cursor;
END;

Program code:
#include 
#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        cur->prepareQuery("begin  :curs:=sp_mytable; end;");
        cur->defineOutputBindCursor("curs");
        cur->executeQuery();

        sqlrcursor      *bindcur=cur->getOutputBindCursor("curs");
        bindcur->fetchFromBindCursor();

        // print fields from table
        for (int i=0; irowCount(); i++) {
                for (int j=0; jcolCount(); j++) {
                        cout << bindcur->getField(i,j) << ", ";
                }
                cout << endl;
        }

        delete bindcur;

        delete cur;
        delete con;
}

The number of cursors simultaneously available per-connection is set at compile time and defaults to 5.

Getting Column Information

For each column, the API supports getting the name, type and length of each field. All databases support these attributes. The API also supports getting the precision, scale, length of the longest field, and whether the column is nullable, the primary key, unique, part of a key, unsigned, zero-filled, binary, or an auto-incrementing field. However, not all databases support these attributes. If a database doesn't support an attribute, it is always returned as false.

#include 
#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        cur->sendQuery("select * from my_table");
        con->endSession();

        for (int i=0; icolCount(); i++) {
                cout << "Name:          " << cur->getColumnName(i) << endl;
                cout << "Type:          " << cur->getColumnType(i) << endl;
                cout << "Length:        " << cur->getColumnLength(i) << endl;
                cout << "Precision:     " << cur->getColumnPrecision(i) << endl;
                cout << "Scale:         " << cur->getColumnScale(i) << endl;
                cout << "Longest Field: " << cur->getLongest(i) << endl;
                cout << "Nullable:      " << cur->getColumnIsNullable(i) << endl;
                cout << "Primary Key:   " << cur->getColumnIsPrimaryKey(i) << endl;
                cout << "Unique:        " << cur->getColumnIsUnique(i) << endl;
                cout << "Part of Key:   " << cur->getColumnIsPartOfKey(i) << endl;
                cout << "Unsigned:      " << cur->getColumnIsUnsigned(i) << endl;
                cout << "Zero Filled:   " << cur->getColumnIsZeroFilled(i) << endl;
                cout << "Binary:        " << cur->getColumnIsBinary(i) << endl;
                cout << "Auto Increment:" << cur->getColumnIsAutoIncrement(i) << endl;
                cout << endl;
        }

        delete cur;
        delete con;
}

Some databases force column names to upper case, others force column names to lower case, and others still support mixed-case column names. Sometimes, when migrating between databases, you can run into trouble. You can use upperCaseColumnNames() and lowerCaseColumnNames() to cause column names to be converted to upper or lower case, or you can use mixedCaseColumnNames() to cause column names to be returned in the same case as they are defined in the database.

#include 
#include 

main() {

        sqlrconnection      *con=new sqlrconnection("host",9000,"","user","password",0,1);
        sqlrcursor          *cur=new sqlrcursor(con);

        // column names will be forced to upper case
        cur->upperCaseColumnNames();
        cur->sendQuery("select * from my_table");
        con->endSession();

        for (int i=0; icolCount(); i++) {
                cout << "Name:          " << cur->getColumnName(i) << endl;
                cout << endl;
        }

        // column names will be forced to lower case
        cur->lowerCaseColumnNames();
        cur->sendQuery("select * from my_table");
        con->endSession();

        for (int i=0; icolCount(); i++) {
                cout << "Name:          " << cur->getColumnName(i) << endl;
                cout << endl;
        }

        // column names will be the same as they are in the database
        cur->mixedCaseColumnNames();
        cur->sendQuery("select * from my_table");
        con->endSession();

        for (int i=0; icolCount(); i++) {
                cout << "Name:          " << cur->getColumnName(i) << endl;
                cout << endl;
        }

        delete cur;
        delete con;
}
Stored Procedures

Many databases support stored procedures. Stored procedures are sets of queries and procedural code that are executed inside of the database itself. For example, a stored procedure may select rows from one table, iterate through the result set and, based on the values in each row, insert, update or delete rows in other tables. A client program could do this as well, but a stored procedure is generally more efficient because queries and result sets don't have to be sent back and forth between the client and database. Also, stored procedures are generally stored in the database in a compiled state, while queries may have to be re-parsed and re-compiled each time they are sent.

While many databases support stored procedures. The syntax for creating and executing stored procedures varies greatly between databases.

SQL Relay supports stored procedures for most databases, but there are some caveats. Stored procedures are not currently supported when using FreeTDS against Sybase or Microsoft SQL Server. Blob/Clob bind variables are only supported in Oracle 8i or higher. Sybase stored procedures must use varchar output parameters.

Stored procedures typically take input paramters from client programs through input bind variables and return values back to client programs either through bind variables or result sets. Stored procedures can be broken down into several categories, based on the values that they return. Some stored procedures don't return any values, some return a single value, some return multiple values and some return entire result sets.

No Values

Some stored procedures don't return any values. Below are examples, illustrating how to create, execute and drop this kind of stored procedure for each database that SQL Relay supports.

Oracle

To create the stored procedure, run a query like the following.

create procedure testproc(in1 in number, in2 in number, in3 in varchar2) is
begin
        insert into mytable values (in1,in2,in3);
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("begin testproc(:in1,:in2,:in3); end;");
cur->inputBind("in1",1);
cur->inputBind("in2",1.1,2,1);
cur->inputBind("in3","hello");
cur->executeQuery();

To drop the stored procedure, run a query like the following.

drop procedure testproc
Sybase and Microsoft SQL Server

To create the stored procedure, run a query like the following.

create procedure testproc @in1 int, @in2 float, @in3 varchar(20) as
        insert into mytable values (@in1,@in2,@in3)

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("exec testproc");
cur->inputBind("in1",1);
cur->inputBind("in2",1.1,2,1);
cur->inputBind("in3","hello");
cur->executeQuery();

To drop the stored procedure, run a query like the following.

drop procedure testproc
Interbase and Firebird

To create the stored procedure, run a query like the following.

create procedure testproc(in1 integer, in2 float, in3 varchar(20)) as
begin
        insert into mytable values (in1,in2,in3);
        suspend;
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("execute procedure testproc ?, ?, ?");
cur->inputBind("1",1);
cur->inputBind("2",1.1,2,1);
cur->inputBind("3","hello");
cur->executeQuery();

To drop the stored procedure, run a query like the following.

drop procedure testproc
DB2

To create the stored procedure, run a query like the following.

create procedure testproc(in in1 int, in in2 double, in in3 varchar(20)) language sql
begin
        insert into mytable values (in1,in2,in3);
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("call testproc(?,?,?)");
cur->inputBind("1",1);
cur->inputBind("2",1.1,2,1);
cur->inputBind("3","hello");
cur->executeQuery();

To drop the stored procedure, run a query like the following.

drop procedure testproc
Postgresql

To create the stored procedure, run a query like the following.

create function testproc(int,float,varchar(20)) returns void as '
begin
        insert into mytable values ($1,$2,$3);
        return;
end;' language plpgsql

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("select testproc(:in1,:in2,:in3)");
cur->inputBind("in1",1);
cur->inputBind("in2",1.1,2,1);
cur->inputBind("in3","hello");
cur->executeQuery();

To drop the stored procedure, run a query like the following.

drop procedure testproc

Single Values

Some stored procedures return single values. Below are examples, illustrating how to create, execute and drop this kind of stored procedure for each database that SQL Relay supports.

Oracle

In Oracle, stored procedures can return values through output parameters or as return values of the procedure itself.

Here is an example where the procedure itself returns a value. Note that Oracle calls these functions.

To create the stored procedure, run a query like the following.

create function testproc(in1 in number, in2 in number, in3 in varchar2) returns number is
begin
        return in1;
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("select testproc(:in1,:in2,:in3) from dual");
cur->inputBind("in1",1);
cur->inputBind("in2",1.1,2,1);
cur->inputBind("in3","hello");
cur->executeQuery();
char    *result=cur->getField(0,0);

To drop the stored procedure, run a query like the following.

drop function testproc

Here is an example where the value is returned through an output parameter.

To create the stored procedure, run a query like the following.

create procedure testproc(in1 in number, in2 in number, in3 in varchar2, out1 out number) as
begin
        out1:=in1;
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("begin testproc(:in1,:in2,:in3,:out1); end;");
cur->inputBind("in1",1);
cur->inputBind("in2",1.1,2,1);
cur->inputBind("in3","hello");
cur->defineOutputBind("out1",20);
cur->executeQuery();
char    *result=cur->getOutputBind("out1");

To drop the stored procedure, run a query like the following.

drop procedure testproc
Sybase and Microsoft SQL Server

In Sybase and Microsoft SQL Server, stored procedures return values through output parameters rather than as return values of the procedure itself.

To create the stored procedure, run a query like the following.

create procedure testproc @in1 int, @in2 float, @in3 varchar(20), @out1 int output as
        select @out1=convert(varchar(20),@in1)

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("exec testproc");
cur->inputBind("in1",1);
cur->inputBind("in2",1.1,2,1);
cur->inputBind("in3","hello");
cur->defineOutputBind("out1",20);
cur->executeQuery();
char    *result=cur->getOutputBind("out1");

To drop the stored procedure, run a query like the following.

drop procedure testproc
Interbase and Firebird

To create the stored procedure, run a query like the following.

create procedure testproc(in1 integer, in2 float, in3 varchar(20)) returns (out1 integer) as
begin
        out1=in1;
        suspend;
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("select * from testproc(?,?,?)");
cur->inputBind("1",1);
cur->inputBind("2",1.1,2,1);
cur->inputBind("3","hello");
cur->executeQuery();
char    *result=cur->getField(0,0);

Alternatively, you can run a query like the following and receive the result using an output bind variable. Note that in Interbase/Firebird, input and output bind variable indices are distict from one another. The index of the output bind variable is 1 rather than 4, even though there were 3 input bind variables.

cur->prepareQuery("execute procedure testproc ?, ?, ?");
cur->inputBind("1",1);
cur->inputBind("2",1.1,2,1);
cur->inputBind("3","hello");
cur->defineOutputBind("1",20);
cur->executeQuery();
char    *result=cur->getOutputBind("1");

To drop the stored procedure, run a query like the following.

drop procedure testproc
DB2

In DB2, stored procedures return values through output parameters rather than as return values of the procedure itself.

To create the stored procedure, run a query like the following.

create procedure testproc(in in1 int, in in2 double, in in3 varchar(20), out out1 int) language sql
begin
        set out1 = in1;
end

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("call testproc(?,?,?,?)");
cur->inputBind("1",1);
cur->inputBind("2",1.1,2,1);
cur->inputBind("3","hello");
cur->defineOutputBind("4",25);
cur->executeQuery();
char    *result=cur->getOutputBind("4");

To drop the stored procedure, run a query like the following.

drop procedure testproc
Postgresql

To create the stored procedure, run a query like the following.

create function testfunc(int,float,char(20)) returns int as '
declare
        in1 int;
        in2 float;
        in3 char(20);
begin
        in1:=$1;
        return;
end;
' language plpgsql

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("select * from testfunc(:in1,:in2,:in3)");
cur->inputBind("in1",1);
cur->inputBind("in2",1.1,4,2);
cur->inputBind("in3","hello");
cur->executeQuery();
char    *result=cur->getField(0,0);

To drop the stored procedure, run a query like the following.

drop function testfunc(int,float,char(20))

Multiple Values

Some stored procedures return multiple values. Below are examples, illustrating how to create, execute and drop this kind of stored procedure for each database that SQL Relay supports.

Oracle

In Oracle, stored procedures can return values through output parameters or as return values of the procedure itself. If a procedure needs to return multiple values, it can return one of them as the return value of the procedure itself, but the rest must be returned through output parameters.

To create the stored procedure, run a query like the following.

create procedure testproc(in1 in number, in2 in number, in3 in varchar2, out1 out number, out2 out number, out3 out varchar2) is
begin
        out1:=in1;
        out2:=in2;
        out3:=in3;
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

cur->prepareQuery("begin testproc(:in1,:in2,:in3,:out1,:out2,:out3); end;");
cur->inputBind("in1",1);
cur->inputBind("in2",1.1,2,1);
cur->inputBind("in3","hello");
cur->defineOutputBind("out1",20);
cur->defineOutputBind("out2",20);
cur->                                   
阅读(152702) | 评论(0) | 转发(1) |
2

上一篇:终于忍无可忍了

下一篇:SQL relay的C接口

给主人留下些什么吧!~~
评论热议
请登录后评论。

登录 注册