I was wondering if I could upload a file (with an mp3 extension) to MySQL Database.
I am using C++ for my application.
Thanks.
Turorial
You will need to create a database, and a table, the table needs to have the following columns.
[name] -> [column data type]
id -> PRIMARY INT AUTOINCREAMENTAL
filename -> vchar(255)
data -> TEXT
then use the example code below, and do an insert into this newly created table.
Guide
You will need to follow the MySQL Connector/C++ 8.0 Developer Guide
This manual describes how to install and configure MySQL Connector/C++ 8.0, which provides C++ and plain C interfaces for communicating with MySQL servers, and how to use Connector/C++ to develop database applications.
Requirements
Connector/C++ 8.0 is highly recommended for use with MySQL Server 8.0 and 5.7. Please upgrade to Connector/C++ 8.0.
Example code
/* Copyright 2008, 2010, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
There are special exceptions to the terms and conditions of the GPL
as it is applied to this software. View the full text of the
exception in file EXCEPTIONS-CONNECTOR-C++ in the directory of this
software distribution.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
AS _message'..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column data by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
Related
The new thrust::tabulate function works for me on the host but not on the device. The device is a K20x with compute capability 3.5. The host is an Ubuntu machine with 128GB of memory. Help?
I think that the unified addressing is not the problem since I can sort a unifiedly addressed array on the device.
#include <iostream>
#include <thrust/device_vector.h>
#include <thrust/execution_policy.h>
#include <thrust/tabulate.h>
#include <thrust/version.h>
using namespace std;
// Print an expression's name then its value, possible followed by a
// comma or endl. Ex: cout << PRINTC(x) << PRINTN(y);
#define PRINT(arg) #arg "=" << (arg)
#define PRINTC(arg) #arg "=" << (arg) << ", "
#define PRINTN(arg) #arg "=" << (arg) << endl
// Execute an expression and check for CUDA errors.
#define CE(exp) { \
cudaError_t e; e = (exp); \
if (e != cudaSuccess) { \
cerr << #exp << " failed at line " << __LINE__ << " with error " << cudaGetErrorString(e) << endl; \
exit(1); \
} \
}
const int N(10);
int main(void) {
int major = THRUST_MAJOR_VERSION;
int minor = THRUST_MINOR_VERSION;
cout << "Thrust v" << major << "." << minor
<< ", CUDA_VERSION: " << CUDA_VERSION << ", CUDA_ARCH: " << __CUDA_ARCH__
<< endl;
cout << PRINTN(N);
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, 0);
if (!prop.unifiedAddressing) {
cerr << "Unified addressing not available." << endl;
exit(1);
}
cudaGetDeviceProperties(&prop, 0);
if (!prop.canMapHostMemory) {
cerr << "Can't map host memory." << endl;
exit(1);
}
cudaSetDeviceFlags(cudaDeviceMapHost);
int *p, *q;
CE(cudaHostAlloc(&p, N*sizeof(int), cudaHostAllocMapped));
CE(cudaHostAlloc(&q, N*sizeof(int), cudaHostAllocMapped));
thrust::tabulate(thrust::host, p, p+N, thrust::negate<int>());
thrust::tabulate(thrust::device, q, q+N, thrust::negate<int>());
for (int i=0; i<N; i++)
cout << PRINTC(i) << PRINTC(p[i]) << PRINTN(q[i]);
}
Output:
Thrust v1.7, CUDA_VERSION: 6000, CUDA_ARCH: 0
N=10
i=0, p[i]=0, q[i]=0
i=1, p[i]=-1, q[i]=0
i=2, p[i]=-2, q[i]=0
i=3, p[i]=-3, q[i]=0
i=4, p[i]=-4, q[i]=0
i=5, p[i]=-5, q[i]=0
i=6, p[i]=-6, q[i]=0
i=7, p[i]=-7, q[i]=0
i=8, p[i]=-8, q[i]=0
i=9, p[i]=-9, q[i]=0
The following does not add any info content to my post but is required before stackoverflow will accept it: Much of the program is error checking and version checking.
The problem appears to be fixed in the thrust master branch at the moment. This master branch currently identifies itself as Thrust v1.8.
I ran your code with CUDA 6RC (appears to be what you are using) and I was able to duplicate your observation.
I then updated to the master branch, and removed the __CUDA_ARCH__ macro from your code, and I got the expected results (host and device tabulations match).
Note that according to the programming guide, the __CUDA_ARCH__ macro is only defined when it's used in code that is being compiled by the device code compiler. It is officially undefined in host code. Therefore it's acceptable to use it as follows in host code:
#ifdef __CUDA_ARCH__
but not as you are using it. Yes, I understand the behavior is different between thrust v1.7 and thrust master in this regard, but that appears to (also) be a thrust issue, that has been fixed in the master branch.
Both of these issues I expect would be fixed whenever the next version of thrust gets incorporated into an official CUDA drop. Since we are very close to CUDA 6.0 official release, I'd be surprised if these issues were fixed in CUDA 6.0.
Further notes about the tabulate issue:
One workaround would be to update thrust to master
Issue doesn't appear to be specific to thrust::tabulate in my testing. Many thrust functions that I tested seem to fail in that when used with thrust::device and raw pointers, they fail to write values correctly (seem to write all zeroes), but they do seem to be able to read values correctly (e.g. thrust::reduce seems to work)
Another possible workaround is to wrap your raw pointers with thrust::device_ptr<> using thrust::device_ptr_cast<>(). That seemed to work for me as well.
I'm having a trouble in trying to send a char (i.e. "R") from my qt5 application on WIN7 to comport which is connected to an Arduino.
I intend to blink a led on Arduino and my arduino part works OK.
Here is my qt code:
#include <QTextStream>
#include <QCoreApplication>
#include <QtSerialPort/QSerialPortInfo>
#include <QSerialPort>
#include <iostream>
#include <QtCore>
QT_USE_NAMESPACE
using namespace std;
QSerialPort serial;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextStream out(stdout);
QList<QSerialPortInfo> serialPortInfoList = QSerialPortInfo::availablePorts();
out << QObject::tr("Total number of ports available: ") << serialPortInfoList.count() << endl;
foreach (const QSerialPortInfo &serialPortInfo, serialPortInfoList) {
out << endl
<< QObject::tr("Port: ") << serialPortInfo.portName() << endl
<< QObject::tr("Location: ") << serialPortInfo.systemLocation() << endl
<< QObject::tr("Description: ") << serialPortInfo.description() << endl
<< QObject::tr("Manufacturer: ") << serialPortInfo.manufacturer() << endl
<< QObject::tr("Vendor Identifier: ") << (serialPortInfo.hasVendorIdentifier() ? QByteArray::number(serialPortInfo.vendorIdentifier(), 16) : QByteArray()) << endl
<< QObject::tr("Product Identifier: ") << (serialPortInfo.hasProductIdentifier() ? QByteArray::number(serialPortInfo.productIdentifier(), 16) : QByteArray()) << endl
<< QObject::tr("Busy: ") << (serialPortInfo.isBusy() ? QObject::tr("Yes") : QObject::tr("No")) << endl;
}
serial.setPortName("COM5");
serial.open(QIODevice::ReadWrite);
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
if(!serial.isOpen())
{
std::cout<<"port is not open"<<endl;
//serial.open(QIODevice::ReadWrite);
}
if(serial.isWritable()==true)
{
std::cout<<"port writable..."<<endl;
}
QByteArray data("R");
serial.write(data);
serial.flush();
std::cout<<"value sent!!! "<<std::endl;
serial.close();
return 0;
}
My source code consists of two parts,
1- serialportinfolist .... which works just fine
2- opening and writing data... I get no issue when running the code and the display shows the result as if nothing has gone wrong!
HOWEVER, the led on the board does not turn on when I run this code.
I test this with Arduino Serial Monitor and it turns on but cant turn on from Qt.
Are you waiting for cr lf (0x0D 0x0A) in your arduino code?
QByteArray ba;
ba.resize(3);
ba[0] = 0x5c; //'R'
ba[1] = 0x0d;
ba[2] = 0x0a;
Or append it to your string with
QByteArray data("R\r\n");
Or
QByteArray data("R\n");
I think I have found a partial solution but it is still incomplete.
When I press debug the first time, qt does not send any signal to Arduino, but when I press debug for the second time it behaves as expected.
So, is'nt it so weird that one has to run it twice to get it working???
Let me know if the problem exists somewhere else,
any help...
I have a weird error that I don't understand when I initialize a device vector using a functional.
I want to create a device_vector of size 1000 with elements:
A[i] = i*0.05;
Here is my code: (seen from example here : Thrust - Initial device_vector)
#include <thrust/device_vector.h>
#include <thrust/functional.h>
#include <thrust/iterator/counting_iterator.h>
using namespace thrust::placeholders;
int main(void)
{
thrust::device_vector<float> A(
thrust::make_transform_iterator(
thrust::counting_iterator<float>(0),_1*0.05),
thrust::make_transform_iterator(
thrust::counting_iterator<float>(0),_1*0.05) + 1000);
std::cout << "--------------------------" << std::endl;
std::cout << "A[0] is : " << A[0] << std::endl;
std::cout << "A[1] is : " << A[1] << std::endl;
std::cout << "A[100] is : " << A[100] << std::endl;
std::cout << "A[500] is : " << A[500] << std::endl;
return 0;
}
The code compiles fine (using thrust v1.6), but when I try to access any value of my device vector (such as A[0]), I get a runtime error.
What am I doing wrong? This is probably very basic, but it's late Friday night, and somehow I can't see it!
Thanks a lot for the help.
Thrust programs frequently will not behave correctly when compiled with the -G switch, so it's recommended not to use that with thrust.
This specific behavior may vary with thrust versions, and may improve over time with newer thrust versions. But in general, at the moment if you're having trouble with thrust code, try compiling without the -G switch.
Device code will frequently run faster when compiled without the -G switch as well, so in general -G should only be used when you expect to do device code debugging (e.g. with Nsight VSE or cuda-gdb), and there may also be other special cases where you want to use -G for test purposes, if you are focusing specifically on some aspect of device code generation. Otherwise, you should not compile codes with -G as a general practice.
I've been trying to get working MySQL example with Visual Studio 2010 on Windows 7 (x64). I don't have problems on Linux, however, I get a lot errors on Windows. This is my code (I've copied from some site to test if it really won't work)
/* Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
There are special exceptions to the terms and conditions of the GPL
as it is applied to this software. View the full text of the
exception in file EXCEPTIONS-CONNECTOR-C++ in the directory of this
software distribution.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include <mysql_connection.h>
#include <driver.h>
#include <exception.h>
#include <resultset.h>
#include <statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' » AS _message'..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
// cout << "(" << __FUNCTION__ << ") on line " » << __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
hen I tried linking to the static library mysqlcppconn-static.lib. This produces the unresolved errors below. :
1>xedownload.obj : error LNK2019: unresolved external symbol
"__declspec(dllimport) public: class std::basic_string<char,struct
std::char_traits<char>,class std::allocator<char> > const & __thiscall
sql::SQLException::getSQLState(void)const "(__imp_?getSQLState#SQLException#sql##QBEABV?$basic_string#DU?$char_traits#D#std##V?$alloc ator#D#2##std##XZ) referenced in function __catch$_main$0
1>xedownload.obj : error LNK2019: unresolved external symbol "__declspec(dllimport)
public: int __thiscall sql::SQLException::getErrorCode(void)const "(__imp_?getErrorCode#SQLException#sql##QBEHXZ) referenced in function __catch$_main$0
1>xedownload.obj : error LNK2019: unresolved external symbol "__declspec(dllimport)
public: __thiscall sql::SQLString::~SQLString(void)" (__imp_??1SQLString#sql##QAE#XZ) referenced in function _main
1>xedownload.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall sql::SQLString::SQLString(char const * const)" (__imp_??0SQLString#sql##QAE#QBD#Z) referenced in function _main
1>xedownload.obj : error LNK2019: unresolved external symbol __imp__get_driver_instance referenced in function _main
1>xedownload.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const & __thiscall sql::SQLString::asStdString(void)const " (__imp_?asStdString#SQLString#sql##QBEABV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##XZ) referenced in function "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl std::operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class sql::SQLString const &)" (??6std##YAAAV?$basic_ostream#DU?$char_traits#D#std###0#AAV10#ABVSQLString#sql###Z)
1>c:\users\avi\documents\visual studio 2010\Projects\xedownload\Debug\xedownload.exe : fatal error LNK1120: 6 unresolved externals
I think you are running win32, but in fact your library is 64-bit, so you need to see your system installed MySQL Connector C++ 1.1.6 in which the next, in the end is 64-bit or 32-bit. Running a 32-bit program requires the installation of a 32-bit library, which requires 64-bit libraries and header files to run 64-bit programs. VSxxxx special attention to the development process
In an XMLRPC server that I'm working on (based off xmlrpc-c) the threads may want to make a MySQL connection to retrieve some data, using the following function:
Distribution getEntitySetFromMysql( int id ) {
Distribution result;
try {
sql::Driver *driver = get_driver_instance();
sql::Connection *con = driver->connect( (std::string)DBHOST, (std::string)USER, (std::string)PASSWORD);
con->setSchema( (std::string)DATABASE );
sql::Statement *stmt = con->createStatement();
std::stringstream query;
query << "SELECT concept_id, weight FROM entity_set_lines WHERE entity_set_id = " << id;
sql::ResultSet *res = stmt->executeQuery ( query.str() );
while (res->next()) {
result[ res->getInt("concept_id") ] = res->getDouble("weight");
}
delete res;
delete stmt;
con->close();
delete con;
} catch (sql::SQLException &e) {
std::cout << "ERROR: SQLException in " << __FILE__;
std::cout << " (" << __func__<< ") on line " << __LINE__ << std::endl;
std::cout << "ERROR: " << e.what();
std::cout << " (MySQL error code: " << e.getErrorCode();
std::cout << ", SQLState: " << e.getSQLState() << ")" << std::endl;
if (e.getErrorCode() == 1047) {
std::cout << "\nYour server does not seem to support Prepared Statements at all. ";
std::cout << "Perhaps MYSQL < 4.1?" << std::endl;
}
} catch (std::runtime_error &e) {
std::cout << "ERROR: runtime_error in " << __FILE__;
std::cout << " (" << __func__ << ") on line " << __LINE__ << std::endl;
std::cout << "ERROR: " << e.what() << std::endl;
}
return result;
}
All works fine, but after a thread runs this code and successfully returns its result, the thread remains hanging and does not exit. What is wrong with this approach? How fundamentaly wrong is this? Is the MySQL connector thread safe?
While Googling around for a solutions, I came across mentions of sql::Driver::threadInit() and sql::Driver::threadEnd(). However, as I was on version 1.0.5 of the C++ Connector, these functions were not available to me. Adding a driver->threadInit(); after getting a driver instance and driver->threadEnd(); at the end of my function, this problem was resolved.
The following is the mention of this thread init and end functionality in MySQL's 1.1.0 change history:
Added Driver::threadInit() and Driver::threadEnd() methods. Every
thread of a threaded client must call Driver::threadInit() at the very
start of the thread before it does anything else with Connector/C++
and every thread must call Driver::threadEnd() when it finishes. You
can find an example demonstrating the use in examples/pthreads.cpp. It
is strongly discouraged to share connections between threads. It is
theoretically possible, if you set certain (undocumented) mutexes, but
it is not supported at all. Use one connection per thread. Do not have
two threads using the same connection at the same time. Please check
the C API notes on threading on the MySQL manual. Connector/C++ wraps
the C API. (Lawrin, Andrey, Ulf)
TL;DR: If you come across this problem, make sure that your version of the C++ MySQL Connector is >= 1.1.0 and use the sql::Driver::threadInit() and sql::Driver::threadEnd() methods to surround your connection code.
Two thoughts:
libmysql isn't fully thread safe.
the way your code is structured you will leak memory if an exception occurs. you might be better served by either declaring your variables outside the try/catch and using a finally (or local equivalent) to ensure proper cleanup or using smart pointers (if available).
Since you don't show any of the calling or surrounding code it's hard to tell what's actually going on. Do you check the exit code of the thread when it's supposedly done? Can you attach it in a debugger to see what it's doing instead of closing?
Actually :
DO NOT USE : sql::Driver::threadInit() nor sql::Driver::threadEnd()
BECAUSE : you are already using try()
YOU FORGOT :
res->close();
stmt->close();
con->close();
delete res;
delete stmt;
delete con;
EXAMPLE :
int connection_and_query_func()
{
/*connection and query variables*/
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
int err_exception_getErrorCode=0;
/*results variables*/
int my_int_from_column_1 = 0;
double my_double_from_column_2 = 0;
....
std:string my_string_from_column_p = "";
try
{
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("address_name", "user_name", "password");
/* Connect to the MySQL database */
con->setSchema("schema_name");
/* Execute MySQL Query*/
stmt = con->createStatement();
res = stmt->executeQuery("your query statement here");
/* Read MySQL Query results per column*/
my_int_from_column_1 = res->getInt(1);
my_double_from_column_2 = res->getDouble(2);
....
my_string_from_column_p = res->getString(p);
/* Close MySQL Connection*/
res->close();
stmt->close();
con->close();
delete res;
delete stmt;
delete con;
};
/* Get last error*/
catch (sql::SQLException &exception)
{
err_exception_getErrorCode = exception.getErrorCode();
};
return(0);
};
CONCLUSION : this can be executed as many times as you want. The function example (connection_and_query_func()) will close MySQL connection properly after it is done - without adding up processes to your MySQL server!!!
FURTHERMORE : read the official manual https://docs.oracle.com/cd/E17952_01/connector-cpp-en/connector-cpp-en.pdf
ALTERNATIVE : if you cannot close properly your connection and query from your program/function side (thus adding up processes to your MySQL server) consider the 2 following options:
1/ set all MySQL timeout parameters to 10 sec. or less (for instance);
2/ write a script that SHOW PROCESSLIST and delete processes that are in SLEEP for too long.
Cheers.