MySQL Connector/C++ declare variable - c++

I want to create a stored procedure with 4 insert and i have this code
Driver * driver = get_driver_instance();
auto_ptr< Connection > vCon(driver->connect(getHost(), getUser(), getPassword()));
vCon->setSchema(getDB());
auto_ptr< Statement > vStmt(vCon->createStatement());
vStmt->execute("DROP PROCEDURE IF EXISTS add");
vStmt->execute("CREATE PROCEDURE add() begin DECLARE vEvId int DEFAULT 0; DECLARE vAdrEvId int DEFAULT 0; insert into adrEv(den) values('test'); select last_insert_id() into vAdrEvId; insert into ev(den,adrEvId) values('test',vAdrEvId); select last_insert_id() into vEvId; ... other insert ... END;");
vStmt->execute("CALL add()");
vStmt->execute("DROP PROCEDURE IF EXISTS add");
whay i get this error # ERR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'add' at line 1 (MySQL error code: 1064, SQLState: 42000 )

ADD is a reserved word for MySQL. Try using a more specific/descriptive procedure name.

Related

C++ MySQL connector execute stored procedure corrupts connection

In a MySQL Database I have a stored procedure defined by the following create statement:
DROP procedure IF EXISTS `get_next_ticket_number`;
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `get_next_ticket_number`()
BEGIN
SELECT IFNULL((SELECT `number`
FROM ticket
ORDER BY `number` DESC
LIMIT 1)+1, 1) as 'next_number';
END$$
DELIMITER ;
In a QT C++ application I'm attempting to call that procedure and use the result later:
std::unique_ptr<sql::PreparedStatement> pstmt;
std::unique_ptr<sql::ResultSet> res;
int next_number = 0;
try
{
pstmt.reset(dbConnection::getInstance()->getDb()->prepareStatement("CALL get_next_ticket_number();"));
res.reset(pstmt->executeQuery());
while(res->next()) {
next_number = res->getInt("next_number");
}
dbConnection::getInstance()->getDb()->commit(); // For good measure...
}
catch (sql::SQLException &e)
{
// Error logging here
}
getInstance()->getDb() returns a copy of the MySQL connector connection, which is setup with setAutoCommit(true) and works fine for all other select, insert, and update queries.
After successfully calling the procedure, all subsequent queries are failing with MySQL error code: 2014, SQLState: "HY000"
Why does this procedure call seem to leave the connection in an occupied state?
Wrapping the call in a do-while fixed the issue:
do {
// execute code
} while (stmt->getMoreResults());

ORA-00947: not enough values when creating object in Oracle

I created a new TYPE in Oracle in order to have parity between my table and a local c++ object (I am using OCCI interface for C++).
In the code I use
void insertRowInTable ()
{
string sqlStmt = "INSERT INTO MY_TABLE_T VALUES (:x)";
try{
stmt = con->createStatement (sqlStmt);
ObjectDefinition *o = new ObjectDefinition ();
o->setA(0);
o->setB(1);
o->setC(2);
stmt->setObject (1, o);
stmt->executeUpdate ();
cout << "Insert - Success" << endl;
delete (o);
}catch(SQLException ex)
{
//exception code
}
The code compiles, connects to db but throws the following exception
Exception thrown for insertRow Error number: 947 ORA-00947: not enough
values
Do I have a problematic "sqlStmt"? Is something wrong with the syntax or the binding?
Of course I have already setup an environment and connection
env = Environment::createEnvironment (Environment::OBJECT);
occiobjm (env);
con = env->createConnection (user, passwd, db);
How many columns are in the table? The error message indicates that you didn't provide enough values in the insert statement. If you only provide a VALUES clause, all columns in the table must be provided. Otherwise you need to list each of the columns you're providing values for:
string sqlStmt = "INSERT INTO MY_TABLE_T (x_col) VALUES (:x)";
Edit:
The VALUES clause is listing placeholder arguments. I think you need to list one for each value passed, e.g.:
string sqlStmt = "INSERT INTO MY_TABLE_T (GAME_ID, VERSION) VALUES (:x1,:x2)"
Have a look at occidml.cpp in the Oracle OCCI docs for an example.

How to update\insert data into a NVARCHAR column using ODBC API

I am trying to update a Sybase table via Microsofts ODBC API. The following is the basics of the C++ I am trying to execute. In table, TableNameXXX, ColumnNameXXX has a type of NVARCHAR( 200 ).
SQLWCHAR updateStatement[ 1024 ] = L"UPDATE TableNameXXX SET ColumnNameXXX = N 'Executive Chair эюя' WHERE PKEYXXX = 'VALUE'";
if( ret = SQLExecDirect( hstmt, ( SQLWCHAR* ) updateStatement, SQL_NTS ) != SQL_SUCCESS )
{
// Handle Error
}
The Sybase database has a CatalogCollation of 1252LATIN1, CharSet of windows-1252, Collation of 1252LATIN1, NcharCharSet of UTF-8 and an NcharCollation of UCA.
Once this works for the Sybase ODBC connection I need to get it to work in various other ODBC drivers for other databases.
The error i get is "[Sybase][ODBC Driver][SQL Anywhere]Syntax error near 'Executive Chair ' on line 1"
If i take out the Unicode characters and remove the N it will update.
Does anyone know how to get this to work? What am I missing?
I wrote a C# .net project using an ODBCConnection to a SQL Server database and am getting "sort of" the same error. I means sort of as this error contains the Unicode Text in the message whereas the Sybase ODBC error has "lost" the unicode.
static void Main(string[] args)
{
using (OdbcConnection odbc = new OdbcConnection("Dsn=UnicodeTest;UID=sa;PWD=password")) // ;stmt=SET NAMES 'utf8';CharSet=utf16"
//using (OdbcConnection odbc = new OdbcConnection("Dsn=Conversion;CharSet=utf8")) // ;stmt=SET NAMES 'utf8';CharSet=utf8
{
try
{
odbc.Open();
string queryString = "UPDATE TableNameXXX SET ColumnNameXXX = N 'Executive Chair эюя' WHERE PKEYXXX = 'AS000008'";
System.Console.Out.WriteLine(queryString);
OdbcCommand command = new OdbcCommand(queryString);
command.Connection = odbc;
int result = command.ExecuteNonQuery();
if( result == 1)
{
System.Diagnostics.Debug.WriteLine("Success");
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}
"ERROR [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near 'Executive Chair эюя'."
There should be no space between the N and the Unicode enclosed string.
"UPDATE TableNameXXX SET ColumnNameXXX = N 'Executive Chair эюя' WHERE PKEYXXX = 'AS000008'"
should be
"UPDATE TableNameXXX SET ColumnNameXXX = N'Executive Chair эюя' WHERE PKEYXXX = 'AS000008'"

C++ ADO stored procedure error: Syntax Error or Access Violation

I am trying to run an SQL stored procedure through ADO in C++. The procedure is called (for argument's sake) testProcedure and expects two parameters: #param1 and #param2. Here is a trimmed version of the code in the execution method:
m_mCommandParameters[_T("param1")] = _T("foo");
m_mCommandParameters[_T("param2")] = _T("bar");
pCommand.CreateInstance(__uuidof(Command));
pCommand->ActiveConnection = link;
pCommand->CommandType = adCmdStoredProc;
pCommand->CommandText = _T("testProcedure");
pCommand->PutPrepared(true);
pCommand->NamedParameters = true;
// Set up the variant to store the parameter values
VARIANT vParamValue;
vParamValue.vt = VT_BSTR;
CString paramCount; // Stores the count for use as parameter name
// Iterate through set parameters and apply them to command
map<CString,CString>::iterator mItr;
for(mItr = m_mCommandParameters.begin(); mItr != m_mCommandParameters.end(); mItr++) {
paramCount = mItr->first;
vParamValue.bstrVal = _bstr_t(mItr->second);
// Append the parameter
if (mItr->second.IsEmpty()) {
_variant_t vtNULL;
vtNULL.vt = VT_NULL;
pCommand->Parameters->Append(
pCommand->CreateParameter(_bstr_t(L"#"+paramCount),adVarChar,adParamInput,10,vtNULL)
);
} else {
pCommand->Parameters->Append(
pCommand->CreateParameter(_bstr_t(L"#"+paramCount),adVarWChar,adParamInput,
//commandParameters[i].GetLength()+1,
sizeof(vParamValue),
_bstr_t(vParamValue))
);
}
}
_variant_t vRecordsAffected;
pRecordSet = pCommand->Execute(&vRecordsAffected,NULL,adCmdStoredProc);
My understanding is that this should essentially execute the following:
testProcedure #param1 = 'foo', #param2 = 'bar'
If I open SQL management studio and run the above it works fine. But when I try and run the C++ I get the error:
database error IDispatch error #3092 80040e14 query : testProcedure;
[Microsoft][ODBC SQL Server Driver]Syntax error or access violation.
I only have SQL express so don't have SQL profiler; I usually use Express Profiler but for some reason it doesn't display any trace on stored procedured. So I am not sure how to start debugging this.
Thanks!

inserting to database using ado command

I am trying to insert records into a table using adodb using c++.
Stored Proc:
CREATE PROCEDURE [dbo].[dbo.insert_command]
#Id INT OUTPUT,
#Name varchar(25),
#Age int = NULL
-- WITH ENCRYPTION
AS
...
Declaring the commands:
TESTHR(m_pInsertCommand.CreateInstance(__uuidof(Command)));
m_pInsertCommand>ActiveConnection = m_pConnection;
m_pInsertCommand>CommandText = L"dbo.insert_command";
m_pInsertCommand>Parameters->Append(m_pInsertCommand->CreateParameter(L"Id", adInteger, adParamOutput, 4, vtNull));
m_pInsertCommand>Parameters->Append(m_pInsertCommand->CreateParameter(L"Name", adVarChar, adParamInput, m_lLabelLength));
m_pInsertCommand>Parameters->Append(m_pInsertCommand->CreateParameter(L"Age", adInteger, adParamInput, sizeof(long), vtNull));
Setting the parameters:
dbConnection.m_pInsertCommand->Parameters->Item[L"Id"]->Value = vtNull;
dbConnection.m_pInsertCommand->Parameters->Item[L"Name"]->Value = (BSTR) m_Name;
dbConnection.ExecuteCommand(dbConnection.m_pInsertCommand, adCmdStoredProc | adExecuteNoRecords);
Id = (long) dbConnection.m_pInsertDefectCommand->Parameters->Item[L"Id"]->Value;
Trace through SQL Profiler:
declare #p1 int
set #p1=16
exec dbo.insert_Command #p1 output,'Name',NULL
select #p1
My question is why is the command generating the parameter #p1 in the sql statement. this is causing the logic to change as I am trying to insert a record if the parameter id is null.
Any suggestions for why this is happening?
Thanks in advance