Connecting to a MySQL database with an ESP8266WiFi chip - mysql

I'm trying to connect to a remote MySQL database directly from my arduino to do some telemetry on some hardware. However the code gets stuck while connecting to the db, and gives always the answer "no db found". Where am I wrong?
I'm sure that I'm correct with the user/pass thing, however I really can't figure out why it won't connect to the db to execute the query.
#include <ESP8266WiFi.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
char ssid[] = "mywifissid";
char pass[] = "mywifipass";
char mysqlUser[] = "mysqluser";
char mysqlPass[] = "mysqlpassword";
char id[] = "someidforthearduino";
WiFiClient wifiClient;
MySQL_Connection mysqlConnection ((Client *)&wifiClient);
IPAddress mysqlServer (/*some kind of address for the mySQL server*/);
bool is_Sending = false;
char queryToExecute[128];
char queryUpdate[] = "somequery";
int nPresses = 0;
void setup() {
Serial.begin(115200);
Serial.println("Inizializzazione pin in corso...");
pinMode(D4, INPUT_PULLUP);
Serial.println("Connessione alla rete in corso...");
WiFi.disconnect();
WiFi.begin(ssid,pass);
while(WiFi.status() != WL_CONNECTED) {
delay(200);
Serial.print(".");
}
Serial.println("");
Serial.print("Connesso con ip ");
Serial.println(WiFi.localIP());
Serial.println("Inizializzazione completata");
}
void loop() {
if (!digitalRead(D4) && !is_Sending) {
is_Sending = true;
nPresses++;
Serial.println("Rilevata pressione tasto. Connessione in corso...");
if (mysqlConnection.connect(mysqlServer,3306,mysqlUser,mysqlPass)) {
Serial.println("");
Serial.println("Connesso. Inserimento dato...");
sprintf(queryToExecute, queryUpdate, nPresses, id);
MySQL_Cursor *c = new MySQL_Cursor(&mysqlConnection);
c->execute(queryToExecute);
delete c;
Serial.println("Aggiornamento effettuato!");
} else {
Serial.println("No db found.");
}
mysqlConnection.close();
is_Sending = false;
}
}

I figured it out. The code is correct, I just typed the wrong IP for the MySQL server! I discovered it by opening the command prompt and pinging the host name;

Related

The connection between my arduino board and my telegram channel is not working

Im trying to connect a ldr sensor to telegram bot, so that i know if the lights are tripping or not, but it seems like the tripped messages aren't going through. I tried to restart the chip, but it keeps showing "testconnection NOK"Can someone help me to see if there are anyways to troubleshoot this issue? Below is the code used for my arduino.
#include <WiFiClient.h> //CLIENT LIBRARY
#include <ESP8266WebServer.h> //WEBSERVICER LIBRARY
#include <ESP8266HTTPClient.h> //HTTP CLIENT LIBRARY
#include "CTBot.h" //TELEGRAM BOT LIBRARY
CTBot myBot; //INITIALIZE TELEGRAM BOT VARIABLE
String ssid = "CGA-Farm" ; // ASSIGN SSID VARIABLE WITH WIFI SSID
String pass = "0003606367"; // ASSIGN PASS VARIABLE WITH WIFI PASSWORD
String token = "1715253121:AAHqI4O2mt11ono-wFQ-_p5UfVpu0OeekeY"; // TELEGRAM BOT TOKEN RETRIEVED FROM BOTFATHER
int CNT = 0;
void setup() {
Serial.begin(9600);
Serial.println("Starting TelegramBot...");
myBot.wifiConnect(ssid, pass); // CONNECT ESP TO ACCESS POINT
myBot.setTelegramToken(token); // SET TELEGRAM BOT TOKEN
if (myBot.testConnection())// DEBUG CONNECTION
Serial.println("\ntestConnection OK");
else
Serial.println("\ntestConnection NOK");
}
void loop() {
float reading = analogRead(A0);
Serial.println(reading);
delay(1000);
if (reading < 800)
{
if (CNT < 1)
{
Serial.println("No light!");
myBot.sendMessage(-1001412490907,"GR1 Zone1 tripped!");
CNT = CNT + 1;
}
} else
{
CNT = 0;
}
}
Maybe your error is in the Serial.begin(9600) because the baud rate of the Arduino is not compatible with the Telegram bot. Try to change the value 9600 with this number :
115200

Connecting Arduino to wunderground using ESP8266

I'm trying to use an ESP8266 and Arduino Uno to connect to wunderground and get the JSON file to get the current weather. With my code I am connecting to the server fine. What seems to be the issue is that it's not giving me the whole return file.
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial esp8266(8, 9);
bool flag = true;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
esp8266.begin(9600);
}
void loop() {
if (flag) {
String cmd;
int length;
cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += "api.wunderground.com";
cmd += "\",80";
esp8266.println(cmd);
Serial.println(cmd);
delay(2000);
Serial.write(esp8266.read());
if (esp8266.find("CONNECT")) {
Serial.println("CONNECT found so your connected");
}
String action;
action = "GET http://api.wunderground.com/api/APIKEY/conditions/q/Canada/Regina.json HTTP/1.0\r\n\r\n";
length = action.length();
cmd = "AT+CIPSEND=";
cmd += length;
esp8266.println(cmd);
Serial.println(cmd);
delay(5000);
if (esp8266.find(">")) {
Serial.print(">");
} else {
esp8266.println("AT+CIPCLOSE");
Serial.println(F("connect timeout"));
}
esp8266.println(action);
Serial.println(action);
delay(700);
String test = "";
while (esp8266.available()) {
char c = esp8266.read();
test += c;
}
Serial.println(test);
flag = false;
Serial.println("Flag is false");
}
}
Running this code give me the following result:
AT+CIPSTART="TCP","api.wunderground.com",80
ACONNECT found so your connected
AT+CIPSEND=97
GET http://api.wunderground.com/api/7287eb3ace065563/conditions/q/Canada/Regina.json HTTP/1.0
busy s...
Recv 97 bytes
SEND OK
+IPD,1460:HTTP/1.0:"0.1",
"termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
"
Flag is false
As you can see I only get a snippet of the JSON file. I'm not sure what the problem is.
It's not sending JSON at all. It detected that your Arduino/ESP combo was not a human, and is scolding you, letting you know that you are in breach of the Terms of Service, as described in http://www.wunderground.com/weather/api/d/terms.html. You need to set some headers, to masquerade as a browser and thus pass as a human user.

set mysql connection behind ssh in groovy script SoapUI

From groovy script in SoapUI I need to connect to a mysql database to perform some queries. The problem is that due to security reasons no external access is possible.
Therefore it is required to get an ssh access (like a tunnel) and invoke mysql locally.
Initially I was reading the below project properties and then connect to mysql:
ServerUrl=jdbc:mysql://10.255.255.122:3306/db
ServerDbUser=user
ServerDbPwd=password
ServerDriver=com.mysql.jdbc.Driver
def url=testRunner.testCase.testSuite.project.getPropertyValue("ServerUrl")
def usr=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbUser")
def pwd=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbPwd")
def driver=testRunner.testCase.testSuite.project.getPropertyValue("ServerDriver")
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver(driver)
sqlServer = Sql.newInstance(url, usr, pwd, driver)`
But this didn't work so now it is required to establish first a ssh connection to the server with the IP 10.255.255.122 and then open the mysql connection locally. So I guess the Server Url will change to:
ServerUrl=jdbc:mysql://127.0.0.1:3306/db
But I don't know how to set first the ssh connection to the server.
Can someone help me with this?
Thanks.
Have a look at http://forum.soapui.org/viewtopic.php?t=15400 and connect to remote mysql database through ssh using java
It will give you an idea about implementing it in soapUI.
Below is the code by Ripon Al Wasim which is available as an answer at the stackoverflow link mentioned above
package mypackage;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UpdateMySqlDatabase {
static int lport;
static String rhost;
static int rport;
public static void go(){
String user = "ripon";
String password = "wasim";
String host = "myhost.ripon.wasim";
int port=22;
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
lport = 4321;
rhost = "localhost";
rport = 3306;
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){System.err.print(e);}
}
public static void main(String[] args) {
try{
go();
} catch(Exception ex){
ex.printStackTrace();
}
System.out.println("An example for updating a Row from Mysql Database!");
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://" + rhost +":" + lport + "/";
String db = "testDB";
String dbUser = "wasim";
String dbPasswd = "riponalwasim123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "UPDATE MyTableName " +
"SET email = 'ripon.wasim#smile.com' WHERE email='peace#happy.com'";
int update = st.executeUpdate(sql);
if(update >= 1){
System.out.println("Row is updated.");
}
else{
System.out.println("Row is not updated.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

warning remove database

my code show this next warning:
QSqlDatabasePrivate::removeDatabase: connection ‘qt_sql_default_connection’
is still in use, all queries will cease to work
This is my code the connection with data base is fine:
QSqlDatabase database::db()
{
return m_db;
}
bool database::connect()
{
m_db = QSqlDatabase::addDatabase("QMYSQL");
m_db.setDatabaseName("aaaa");
m_db.setHostName("192.168.xxx.xxx");
m_db.setUserName("xx");
m_db.setPassword("xxxx");
m_db.setPort(1234);
return m_db.open();
}
void database::close()
{
QString connection;
connection = m_db.connectionName();
m_db.close();
m_db.removeDatabase(connection);
}
m_db is define as:
QSqlDatabase m_db;
and my test is:
database db;
qDebug() << "CONNECT: " << db.connect();
db.close();
How can I fix it?
Thanks you very much.
After you closed it, m_db still holds a reference to the database you configured in connect().
You can reset m_db by assigning a default constructed QSqlDatabase:
void database::close()
{
QString connection;
connection = m_db.connectionName();
m_db.close();
m_db = QSqlDatabase();
m_db.removeDatabase(connection);
}
void database::close()
{
QString connection;
connection = m_db.connectionName();
m_db = QSQlDatabase();
//m_db.close();
m_db.removeDatabase(connection);
}
try this it will work..
Adding an additional scope does the same trick:
QString connectionName;
bool ok = false;
{
QSqlDatabase db = QSqlDatabase::addDatabase(databaseType);
connectionName = db.connectionName();
db.setHostName(hostname);
db.setDatabaseName(databaseName);
db.setUserName(userName);
db.setPassword(password);
ok = db.open();
db.close();
}
QSqlDatabase::removeDatabase(connectionName);
return ok;

Connecting Visual c++ 2008 to MySql

I am trying to connect c++ to mysql.
I am using visual c++ 2008 Express Edition.
//Write a c++ Program to add a user to mysql/
//The User Should be permitted to only "select" entries from the given database
#include<stdio.h>
#include<conio.h>
#include<windows.h>
#include<iostream>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
using namespace std;
//SQL_ACTIVE_CONNECTIONS
//sql::Connection *_con;
//sql::mysql::MySQL_Driver *_driver;
//_driver = sql::mysql::get_mysql_driver_instance();
//_con = _driver->connect("tcp://127.0.0.1:3306", "user", "password");
MYSQL *conn;
MYSQL *newconn;
char USERNAME[100]; //MYSQL username
char PASSWORD[100]; //MYSQL password
void CreateConnection(void); //Create Connection with mysql server.
void SelectDatabase(void); //Create and select database.
void CreateUser(void); //Create New user and grant Permission.
void NewConn(void); //Create new connection with user information
void CreateTable(void); //Create "Product" Table to operate.
void InsertData(void); //insert data into product table.
void DeleteData(void); //Delete data from product table.
void SelectData(void); //Retrieve data From product table;
int main()
{
char ch;
int select;
char uname[100],pass[100];
CreateConnection();
SelectDatabase();
cout<<"\n\nEnter your login infomation\nTo delete and retrieve use ADMIN account\n";
cout<<"If you are new user your account will be create with insert privilege.\n";
cout<<"UserName :";
gets(uname);
mysql_escape_string(USERNAME,uname,strlen(uname)); //Assign username in USERNAME variable.
cout<<"Password :";
gets(pass);
mysql_escape_string(PASSWORD,pass,strlen(pass)); //Assign password in PASSWORD variable
CreateUser();
NewConn();
cout<<"\nSelect option.";
do
{
cout<<"\n1. INSERT\n2. DELETE\n3. RETRIEVE\n";
cin>>select;
switch(select)
{
case 1:
InsertData();
break;
case 2:
DeleteData();
break;
case 3:
SelectData();
break;
default:
printf("Wrong selection \n");
break;
}
cout<<"Do You want to continue.....(Y/N)\n";
}while(('Y'==getchar())||('y'==getchar()));
mysql_close(newconn);
return 0;
}
//Create connection with mysql server with username and password NULL.
void CreateConnection()
{
conn = mysql_init(NULL);
if (conn == NULL)
{
cout<<"Error : %s\n"<<mysql_error(conn);
exit(1);
}
if(mysql_real_connect(conn, "localhost", NULL,NULL, NULL, 0, NULL, 0) == NULL)
{
cout<<"Error : %s\n", mysql_error(conn);
exit(1);
}
}
//select the database, if it is not present then create .
void SelectDatabase()
{
if(mysql_query(conn, "create database user")) //Query for creat3 database USER
{
if(mysql_errno(conn)==1007) //Error number 1007 means database already Exist
{
if(mysql_select_db(conn,"user")) //Query for Selecte database USER
{
cout<<"Error :",mysql_error(conn);
exit(1);
}
}
else
{
cout<<"Error :",mysql_error(conn);
exit(1);
}
}
else //This else part will be executed only if database is create without error
{
if(mysql_select_db(conn,"user")) //Query for Selecte database USER
{
cout<<"Error :",mysql_error(conn);
exit(1);
}
CreateTable(); //creating tables in USER database
}
}
//Create account for new user and grant permission
void CreateUser()
{
char cmd[200];
sprintf(cmd,"create user '%s'#'localhost' identified by '%s'",USERNAME,PASSWORD); //prepare query to create user with USERNAME and PASSWORD.
if(mysql_query(conn,cmd))
{
if(mysql_errno(conn)==1396) //Error number 1396 means that user already exists
{
cout<<"WELCOME %s\n"<<USERNAME;
}
else
{
cout<<mysql_error(conn);
exit(1);
}
}
else
{
sprintf(cmd,"grant insert on user.* to '%s'#'localhost'",USERNAME); //grant permission for created user.
if(mysql_query(conn,cmd))
{
cout<<mysql_error(conn);
exit(1);
}
else
{
cout<<"Your Account created %S\n"<<USERNAME;
}
}
mysql_close(conn);
}
//create sample table PRODUCT with two coloumn 1.P_ID and 2.P_Name
void CreateTable()
{
if(mysql_query(conn,"CREATE TABLE product (P_Id INT(6) NOT NULL AUTO_INCREMENT,P_NAME VARCHAR(100) NOT NULL,PRIMARY KEY (P_Id));"))
{
cout<<"Error :%s"<<mysql_error(conn);
exit(1);
}
else
{
cout<<"Table created\n";
}
}
//create connection with USERNAME and PASSWORD supplied by user.
void NewConn()
{
newconn = mysql_init(NULL);
if (newconn == NULL) {
cout<<"Error : %s\n"<< mysql_error(newconn);
exit(1);
}
if (mysql_real_connect(newconn, "localhost", USERNAME,PASSWORD,"user", 0, NULL, 0) == NULL) {
cout<<"Error : %s\n"<< mysql_error(newconn);
exit(1);
}
}
//insert data into Product table.
void InsertData()
{
char cmd[200];
char pname[100],PNAME[100];
cout<<"Enter Product Name :"; //product name that would be added in PRODUCT details
cin>>pname;
mysql_escape_string(PNAME,pname,strlen(pname));
cout<<cmd<<"insert into Product (P_NAME) values('%s')"<<pname);
if(mysql_query(newconn,cmd))
{
cout<<"Error :%s"<<mysql_error(newconn);
exit(1);
}
else
{
cout<<"product added\n";
}
}
//Delete data from product table, it require ADMIN privilege.
void DeleteData()
{
char cmd[200];
char pname[100],PNAME[100];
cout<<"Enter Product Name :"; //Enter product name to delete the details
cout<<pname;
mysql_escape_string(PNAME,pname,strlen(pname));
sprintf(cmd,"delete from Product where P_Name='%s'",pname);//prepare delete query.
if(mysql_query(newconn,cmd))
{
cout<<"Error :%s",mysql_error(newconn);
}
else
{
cout<<"product deleted\n";
}
}
//Retrieve data from Product table, it require ADMIN privilege.
void SelectData()
{
char cmd[200];
char pname[100],PNAME[100];
MYSQL_RES *result;
MYSQL_ROW row;
int num_fields,i;
cout<<"Enter Product Name :"; //Enter product name to see the details
cin>>pname;
mysql_escape_string(PNAME,pname,strlen(pname));
cout<<cmd<<"Select * from Product where P_Name='%s'"<<pname); //prepare select statement
if(mysql_query(newconn,cmd))
{
cout<<"Error :%s"<<mysql_error(newconn);
}
else
{
result = mysql_store_result(conn);
num_fields = mysql_num_fields(result);
cout<<"\nPRODUCT ID\tPRODUCT NAME\n";
cout<<"----------------------------------\n";
while ((row = mysql_fetch_row(result)))
{
for(i = 0; i < num_fields; i++)
{
printf("%s\t\t ", row[i] ? row[i] : "NULL"); //display product information
}
printf("\n");
}
mysql_free_result(result);
}
}
But the Compiler Is not able to link With MySql Project.
I think I need to Link throgh Project->properties something Libraries.
I had installed mysql-connector-c++-1.0.5-win32 from [http://dev.mysql.com/downloads/mirror.php?id=369369] website.
Still it is not able to detect my files.
Please help me.
http://dev.mysql.com/doc/refman/5.1/en/connector-cpp-apps-windows-visual-studio.html
Please read the link and add the references properly. I suggest you read the documentation atleast once since you want to use it.