How do I connect to my web domain's mySQL database using Qt? - mysql

I have a web domain and had already mySql database in it. I wish to connect and retrieve data from the database to my Qt Application. Here is my attempt and my result. (The host name, database name, username and password were just edited).
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setHostName("www.mydomain.com");
db.setDatabaseName("myDatabase");
db.setUserName("myName");
db.setPassword("myPass");
if(!db.open()){
QSqlError err = db.lastError();
qDebug() << err.text();
}
else {
QSqlQuery qry;
qDebug() << "Connected to SQL Database!";
if (qry.exec("select * from dataTable;")){
while(qry.next()){
qDebug() << qry.value(1).toString();
}
}
else {
qDebug() << "ERROR QUERY";
}
qDebug() << "Closing...";
db.close();
}
return a.exec();
}
It shows that it got connected but upon executing a query. It returns an error. Furthermore, I tried changing to an invalid hostname and/or username and it still got connected.

1) Try w/o the semi-colon.
"For SQLite, the query string can contain only one statement at a time." (http://qt-project.org/doc/qt-4.8/qsqlquery.html#exec)
However this is one statement, the interpreter may get confused because of the semi-colon.
2) "Note that the last error for this query is reset when exec() is called." (http://qt-project.org/doc/qt-4.8/qsqlquery.html#exec)
Because this is not a prepared statement, try avoiding exec() so information about the last error is available:
QSqlQuery qry("select * from dataTable");
if(qry.lastError()) {
// ...
}
while(qry.next()) {
qDebug() << qry.value(1).toString();
}

Related

Receiving multicast RTP stream (containing multiple subsessions) from a recorded RTSP session (pcap) using Live555

I have to implement an RTSP Client which connects to an existing RTSP session without being able to send commands to the RTSP Server (recvonly).
To simulate such an environment, I have recorded a RTSP/RTP stream between testH264VideoStreamer and testRTSPClient examples from Live555 with Wireshark, and played it back using tcpreplay while trying to receive stream data with a modified version of testRTSPClient.
I've also stored the SDP information provided by the testH264VideoStreamer as an SDP file.
v=0
o=- 1606317166144671 1 IN IP4 192.168.3.92
s=Session streamed by "testH264VideoStreamer"
i=test.264
t=0 0
a=tool:LIVE555 Streaming Media v2020.10.16
a=type:broadcast
a=control:*
a=source-filter: incl IN IP4 * 192.168.3.92
a=rtcp-unicast: reflection
a=range:npt=0-
a=x-qt-text-nam:Session streamed by "testH264VideoStreamer"
a=x-qt-text-inf:test.264
m=video 18888 RTP/AVP 96
c=IN IP4 232.42.39.62/255
b=AS:500
a=rtpmap:96 H264/90000
a=fmtp:96 packetization-mode=1;profile-level-id=640028;sprop-$
a=control:track1
^#
I've modified the testRTSPClient example so that it connects to the RTP stream only by using the data from the SDP File.
Here are two functions which I use to initialise.
void openSDP(UsageEnvironment& env, char const* sdpFile)
{
const char * rtspURL = "rtsp://192.168.3.92:8554/testStream/";
RTSPClient* rtspClient = ourRTSPClient::createNew(env, rtspURL, RTSP_CLIENT_VERBOSITY_LEVEL);
if(rtspClient == NULL)
{
env << "Failed to create a RTSP client for URL \"" << rtspURL << "\": " << env.getResultMsg();
return;
}
else
{
env << "Connecting to the stream at " << rtspURL;
}
StreamClientState& scs = ((ourRTSPClient*)rtspClient)->scs; // alias
std::vector<char> sdpBuffer;
std::ifstream file(sdpFile, std::ios_base::in | std::ios_base::binary);
file.unsetf(std::ios::skipws);
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
sdpBuffer.reserve(fileSize);
sdpBuffer.insert(sdpBuffer.begin(),
std::istream_iterator<unsigned char>(file),
std::istream_iterator<unsigned char>());
char* const sdpDescription = sdpBuffer.data();
// Create a media session object from this SDP description:
scs.session = MediaSession::createNew(env, sdpDescription);
if(scs.session == NULL)
{
env << *rtspClient << "Failed to create a MediaSession object from the SDP description: " << env.getResultMsg() << "\n";
}
else
if(!scs.session->hasSubsessions())
{
env << *rtspClient << "This session has no media subsessions (i.e., no \"m=\" lines)\n";
}
scs.iter = new MediaSubsessionIterator(*scs.session);
setupNextSubsession(rtspClient);
return;
}
void setupNextSubsession(RTSPClient* rtspClient)
{
UsageEnvironment& env = rtspClient->envir(); // alias
StreamClientState& scs = ((ourRTSPClient*)rtspClient)->scs; // alias
scs.subsession = scs.iter->next();
if(scs.subsession != NULL)
{
if(!scs.subsession->initiate())
{
env << "Failed to initiate the subsession: " << env.getResultMsg();
setupNextSubsession(rtspClient); // give up on this subsession; go to the next one
}
else
{
env << "Initiated the subsession:";
if(scs.subsession->rtcpIsMuxed())
{
env << "client port " << scs.subsession->clientPortNum();
}
else
{
env << "client ports " << scs.subsession->clientPortNum() << "-" << scs.subsession->clientPortNum()+1;
}
scs.subsession->sink = DummySink::createNew(env,
*scs.subsession,
rtspClient->url());
// perhaps use your own custom "MediaSink" subclass instead
if(scs.subsession->sink == NULL)
{
env << "Failed to create a data sink for the subsession: " << env.getResultMsg();
}
env << "Created a data sink for the subsession";
scs.subsession->miscPtr = rtspClient; // a hack to let subsession handler functions get the "RTSPClient" from the subsession
scs.subsession->sink->startPlaying(*(scs.subsession->readSource()),
subsessionAfterPlaying, scs.subsession);
// Also set a handler to be called if a RTCP "BYE" arrives for this subsession:
if(scs.subsession->rtcpInstance() != NULL)
{
scs.subsession->rtcpInstance()->setByeWithReasonHandler(subsessionByeHandler, scs.subsession);
}
// Set up the next subsession, if any:
setupNextSubsession(rtspClient);
}
}
}
Everything initialises without errors, but DummySink receives no data. Any ideas?
I've found out that although wireshark was showing me the incoming packets with valid checksums, udp port received no packets.
I've tried following commands (as sudo) to avoid kernel discarding the packets but they simply don't help on Debian Buster.
sysctl net.ipv4.conf.eth0.rp_filter=0
sysctl net.ipv4.conf.all.rp_filter=0
echo 0 > /proc/sys/net/ipv4/conf/eth0/rp_filter
sysctl -a | grep "\.rp_filter" | awk '{print $1 "=0"}' | xargs sysctl
Basically I've ended up streaming the pcap file from another computer, now I'm able to receive NALUs.

Garrysmod SQL wrapper

require( "mysqloo" )
require( "tmysql4" )
isqldb = mysqloo.connect(DETAILS) || { }
isql = isqldb || { }
--[[---------------------------------------------------------
Initialises iSQL
-----------------------------------------------------------]]
function isql.Connect(addr, u, p, database)
print( "MySQL Connecting:", addr )
isqldb = mysqloo.connect(addr, u, p, database, 3306)
-- tsql hack
tmysql.initialize(addr, u, p, database, 3306)
function isqldb.onConnected()
print( "MySQL Server Version:", self:serverVersion() )
print( "MySQL Server Info:", self:serverInfo() )
print( "MySQL Host Info:", self:hostInfo() )
Msg("iSQL: Sucessfully connected to " .. addr .."\n")
end
function isqldb.onConnectionFailed(self, error)
print( "MySQL Connection Failed! Error:", error )
end
isqldb:connect()
return true
end
--[[---------------------------------------------------------
Query
-----------------------------------------------------------]]
function isql.Query( query, qtype )
if not isqldb then
MsgN("premature db call:")
debug.Trace()
end
local q = isqldb:query( query )
q:start()
q:wait()
if (q:error() == "") then
return q:getData(), true
else
q:error()
return nil, false
end
end
I'm trying to run this to connect and execute ony my mysql server but it won't connect or debug. Can anyone notice where im going wrong?
This is using mysqloo and tmysql4 or should i just use mysqloo
It doesn't even say successfully connected im not sure why
That is not how either Mysqloo nor tmysql4, and you really shouldn't use both of them together.
Lets go ahead now:
It's DATABASE_METATABLE:onConnected() with a ":" not a "."
Same for all methods which are functions in Mysqloo.
Why write queries like that?
You have QUERY_METATABLE:onSuccess(data) and QUERY_METATABLE:onError(err, sql)
Good luck

keep MYSQL connection functional for multiple queries

I am having a very hard time finding information on this topic. I have a running application on a Raspberry Pi where I have an infinite loop with the below code. outside of it i have the MYSQL *con; to be reused. So my code works well the first time, but the second time i get the following error. I thought adding the MYSQL_close() would do the trick but it didn't.
output:
valor: d9274cb5 -651735883
valor: d9274cb5 -651735883
1
This handle is already connected. Use a separate handle for each connection.
code:
uint32_t intVal;
sscanf(&sn_str[1],"%x",&intVal);
fprintf(stderr, "valor: %x %d\n", intVal, intVal);
if (mysql_real_connect(con, "localhost", "rfid", "******",
"Order2Dock", 0, NULL, 0) == NULL)
{
fprintf(stderr, "1 \n");
finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO `Order2Dock`.`Actividad`(`TiempoInicio`,`Proceso_Id`, `Orden_Id`) VALUES (now(),1,1)")) {
fprintf(stderr, "2 \n");
finish_with_error(con);
}
mysql_close(con);
Keep your connect command outside of the loop
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (!$mysqli) {
fprintf(stderr, "1 \n");
finish_with_error(con);
}
Then start the loop, you dont need to connect everytime you loop:
while (1+1 = 2){
if (!$mysqli){
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
}
uint32_t intVal;
sscanf(&sn_str[1],"%x",&intVal);
fprintf(stderr, "valor: %x %d\n", intVal, intVal);
if ($mysqli->query("INSERT INTO `Order2Dock`.`Actividad`(`TiempoInicio`,`Proceso_Id`, `Orden_Id`) VALUES (now(),1,1)") === TRUE) {
echo '<p>Yeah, another query!!</p>';
}
}
Edit: I just added a condition to test if the link is still up, otherwise re-connect to the database.
I was just thinking that if this is an infinite loop running over a Web server like apache or IIS... then something must be configured in order to let the script run forever instead and prevent the web server from timing it out.
Cheers.
w3schools
php refrerence
I heard "mysql" will be deleted on future php..
using "mysqli" and you can use mysqli_multi_query

Groovy: how to use Exceptions or <If> <else> construction with MySQL queries?

I have a query from table of MySQL database, and i want check: have i got this number in table and if not - println that this number not in database, if this number exist - println that this number exist. How i can do that, using Exceptions or (If) (else) construction?
Assuming you're using an in memory hsql db:
def sql = Sql.newInstance( 'jdbc:hsqldb:mem:testDB', // JDBC Url
'sa', // Username
'', // Password
'org.hsqldb.jdbc.JDBCDriver') // Driver classname
def tim = 'tim'
def name = sql.firstRow( "SELECT name FROM users WHERE userid=$tim" )?.name
if( name ) {
println "Name was $name"
}
else {
println "Name not found"
}

mysql call to libmysql.dll to get my app to automatically reconnect after mysql timeout

I am using autohotkey to make mysql calls. The mysql interface was deciphered by referencing a visual basic api to mysql.
I am using the mysql connect calls referenced in this post: http://www.autohotkey.com/forum/viewtopic.php?t=12482
I would like to add a dllcall to replicate this perl call to mysql_options...
mysql_options(mysql, MYSQL_OPT_RECONNECT, &true);
It is my understanding that this call would enable my program to gracefully reconnect to mysql after the standard 8 hour mysql timeout. I want my application to remain up indefinitely.
Here is my code. A reference on googles source code libary suggests that the reconnect constant is 20. Everything works except the mysql_opt_reconnect call.
Can anyone help me determine the proper call to libmysql.dll to get my app to automatically reconnect after mysql timeout has occurred?
;============================================================
; mysql.ahk
;
; Provides a set of functions to connect and query a mysql database
;============================================================
FileInstall, libmysql.dll, %A_AppData%\libmysql.dll, 1
;============================================================
; Connect to mysql database and return db handle
;
; host = DTWRO-WS0061
; user = alan
; password = *******
; database = rush
;============================================================
dbConnect(host,user,password,database){
if (A_IsCompiled) {
ExternDir := A_AppData
} else {
ExternDir := A_WorkingDir
}
hModule := DllCall("LoadLibrary", "Str", ExternDir "\libmySQL.dll")
If (hModule = 0)
{
MsgBox 16, MySQL Error 233, Can't load libmySQL.dll from directory %ExternDir%
ExitApp
}
db := DllCall("libmySQL.dll\mysql_init", "UInt", 0)
If (db = 0)
{
MsgBox 16, MySQL Error 445, Not enough memory to connect to MySQL
ExitApp
}
; figure out how to turn on reconnect call!
; mysql_options(mysql, MYSQL_OPT_RECONNECT, &true);
value := DllCall("libmySQL.dll\mysql_options"
, "UInt", db
, "UInt", 20 ; is this the correct constant which represents MYSQL_OPT_RECONNECT?... see below
, "UInt", 1) ; true
connection := DllCall("libmySQL.dll\mysql_real_connect"
, "UInt", db
, "Str", host ; host name
, "Str", user ; user name
, "Str", password ; password
, "Str", database ; database name
, "UInt", 3306 ; port
, "UInt", 0 ; unix_socket
, "UInt", 0) ; client_flag
If (connection = 0)
{
HandleMySQLError(db, "Cannot connect to database")
Return
}
serverVersion := DllCall("libmySQL.dll\mysql_get_server_info", "UInt", db, "Str")
;MsgBox % "Ping database: " . DllCall("libmySQL.dll\mysql_ping", "UInt", db) . "`nServer version: " . serverVersion
return db
}
;============================================================
; mysql error handling
;============================================================
HandleMySQLError(db, message, query="") { ; the equal sign means optional
errorCode := DllCall("libmySQL.dll\mysql_errno", "UInt", db)
errorStr := DllCall("libmySQL.dll\mysql_error", "UInt", db, "Str")
MsgBox 16, MySQL Error: %message%, Error %errorCode%: %errorStr%`n`n%query%
Return
}
;============================================================
; mysql get address
;============================================================
GetUIntAtAddress(_addr, _offset)
{
local addr
addr := _addr + _offset * 4
Return *addr + (*(addr + 1) << 8) + (*(addr + 2) << 16) + (*(addr + 3) << 24)
}
;============================================================
; process query
;============================================================
dbQuery(_db, _query)
{
local resultString, result, requestResult, fieldCount
local row, lengths, length, fieldPointer, field
query4error := RegExReplace(_query , "\t", " ") ; convert tabs to spaces so error message formatting is legible
result := DllCall("libmySQL.dll\mysql_query", "UInt", _db , "Str", _query)
If (result != 0) {
errorMsg = %_query%
HandleMySQLError(_db, "dbQuery Fail", query4error)
Return
}
requestResult := DllCall("libmySQL.dll\mysql_store_result", "UInt", _db)
if (requestResult = 0) { ; call must have been an insert or delete ... a select would return results to pass back
return
}
fieldCount := DllCall("libmySQL.dll\mysql_num_fields", "UInt", requestResult)
Loop
{
row := DllCall("libmySQL.dll\mysql_fetch_row", "UInt", requestResult)
If (row = 0 || row == "")
Break
; Get a pointer on a table of lengths (unsigned long)
lengths := DllCall("libmySQL.dll\mysql_fetch_lengths" , "UInt", requestResult)
Loop %fieldCount%
{
length := GetUIntAtAddress(lengths, A_Index - 1)
fieldPointer := GetUIntAtAddress(row, A_Index - 1)
VarSetCapacity(field, length)
DllCall("lstrcpy", "Str", field, "UInt", fieldPointer)
resultString := resultString . field
If (A_Index < fieldCount)
resultString := resultString . "|" ; seperator for fields
}
resultString := resultString . "`n" ; seperator for records
}
; remove last newline from resultString
resultString := RegExReplace(resultString , "`n$", "")
Return resultString
}
It took me while to think outside the box, but I finally found a solution that works very well.
I simply added a settimer command to re-connect to the mysql database after 8 hours. 8 hours is the default database connection timeout.
Now the AHK app can remain running indefinitely and is always connected to the database!
Even better... I used an oop class to retain the mysql connection parameters, so that when the mysql connection timed out and a new mysql call is made, it can automatically reconnect.