I created my database in phpMyAdmin from godaddy.com.
But i can't seem to find a way to connect to it.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"
#pragma comment(lib, "mysqlcppconn.lib")
const string server = "myWebsite";
const string username = "username";
const string password = "password";
int main()
{
sql::Driver *driver;
sql::Connection *dbConn;
sql::Statement *stmt;
sql::ResultSet *res;
try
{
driver = get_driver_instance();
}
catch (sql::SQLException e)
{
cout << "Could not get a database driver. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
try
{
dbConn = driver->connect(server, username, password);
}
catch (sql::SQLException e)
{
cout << "Could not connect to database. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
stmt = dbConn->createStatement();
try
{
stmt->execute("USE test");
res = stmt->executeQuery("SELECT * FROM users");
}
catch (sql::SQLException e)
{
cout << "SQL error. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
sql::ResultSetMetaData *res_meta = res -> getMetaData();
int columns = res_meta -> getColumnCount();
while (res->next())
{
for (int i = 1; i <= columns; i++) {
cout << res->getString(i) << " | " ;
}
cout << endl;
}
delete res;
delete stmt;
delete dbConn;
return 0;
}
But i get this error:
Could not connect to database. Error message: Access denied for user 'username'#'IP' (using password: YES)
This code works fine with the local phpmyadmin databases.
So is there any different way to connect to databases that are hosted on a website?
Related
Here's the example function:
#pragma once
#include <string>
#include <iostream>
#include <pqxx/pqxx>
int main()
{
std::string connectionString = "host=ec2-54-74-35-87.eu-west-1.compute.amazonaws.com port=5432 dbname=d8iolcesns1bj4 user=pktunepcutgdqh password=7e3eeef2e01e0d8ae555c7236b1c3375789259dfb6acba41225cc4f55394836c";
try
{
pqxx::connection connectionObject(connectionString.c_str());
pqxx::work worker(connectionObject);
pqxx::result response = worker.exec("SELECT * FROM Users");
for (size_t i = 0; i < response.size(); i++)
{
std::cout << "Id: " << response[i][0] << " Username: " << response[i][1] << " Password: " << response[i][2] << std::endl;
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
system("pause");
}
And I would like to create a class which would hold the data about the connection, like this:
#pragma once
#include <string>
#include <pqxx/pqxx>
class DBLink
{
std::string connectionString = "host=ec2-54-74-35-87.eu-west-1.compute.amazonaws.com port=5432 dbname=d8iolcesns1bj4 user=pktunepcutgdqh password=7e3eeef2e01e0d8ae555c7236b1c3375789259dfb6acba41225cc4f55394836c";
pqxx::connection connectionObject(connectionString.c_str());
pqxx::work worker(connectionObject);
};
but for some reason I get some errors:
is there any way to fix them?
I tried to connect MySQL.
But it seems like something goes wrong and I cannot get it.
I'm basically sending a simple SELECT statement to the database and checking if the operation was successful or not.
Unfortunately, this always outputs "Failed!"
#include <iostream>
#include <string>
#include <mysql/mysql.h>
using namespace std;
int main() {
const char *db = "test";
const char *server = "localhost";
const char *user = "root";
const char *password = "111222";
int port = 3306;
const char *sql = "select 1";
MYSQL *con = mysql_init(NULL);
// con = mysql_init(con);
if (con == NULL) {
cout << "Error:" << mysql_error(con) << endl;
exit(1);
}
MYSQL *new_con = mysql_real_connect(con, server, user, password, db, port, NULL, 0);
if (new_con != NULL) {
cout << "Successful!" << endl;
} else {
cout << "Failed!" << mysql_error(new_con) << endl;
}
int ret = mysql_query(new_con, sql);
if (ret != 0) {
cout << "error: " << mysql_error(new_con) << endl;
}
return 0;
}
Adapted from https://dev.mysql.com/doc/c-api/8.0/en/mysql-real-connect.html
MYSQL mysql;
mysql_init(&mysql);
if (!mysql_real_connect(&mysql,"localhost","root","111222","test",0,NULL,0))
{
fprintf(stderr, "Failed to connect to database: Error: %s\n",
mysql_error(&mysql));
}
else {
cout << "Successfully connected." << endl;
}
What does this sample code print ?
I have a class to connect MySQL database. This class has 4 methods. (insert, getResults etc.) I don't want to create database connection in every method. So i want an init() when we create this object. Is connection pool solution of my problem? How can i solve?
Have 4 methods like that:
bool DataAccessObject::getResults(short int data, std::vector<FaceRecord>* rec)
{
// DataAccessObject *temp = new DataAccessObject();
bool ret = false;
try{
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
sql::PreparedStatement *prepStmt;
/* 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");
std::stringstream s;
s << "SELECT * FROM Amts WHERE "<< data <<" = "<< data <<"";
prepStmt = con->prepareStatement (s.str());
res = prepStmt->executeQuery();
while(res->next()){
tempFR.uuId = res->getInt64("uuId");
tempFR.cameraNo = res->getInt("cameraNo");
tempFR.age = res->getInt("age");
tempFR.gender = res->getInt("gender");
tempFR.time = res->getString("time");
tempFR.image = res->getString("image");
rec->push_back(tempFR);
}
//return true;
ret = true;
}
catch (sql::SQLException &e)
{
std::cout << "# ERR: SQLException in " << __FILE__;
std::cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << std::endl;
std::cout << "# ERR: " << e.what();
std::cout << " (MySQL error code: " << e.getErrorCode();
std::cout << ", SQLState: " << e.getSQLState() << " )" << std::endl;
}
return ret;
}
You can use the C++ Singleton design pattern so that your init is called only once when you create it.
I'm trying to get started with the SQLite on Eclipse CDT on Windows.
#include <iostream>
#include <string>
#include "sqlite3/sqlite3.h"
int main(){
sqlite3 *db;
sqlite3_stmt *res;
const char *errMSG;
const char *tail;
int error = sqlite3_open("test.db",&db);
if (error){
std::cout << "Could not open db." << std::endl;
sqlite3_close(db);
//system("pause");
return 0;
}
std::string query = "SELECT * FROM test";
error = sqlite3_prepare_v2(db, query.c_str(), query.length(), &res, &tail);
if (error != SQLITE_OK){
std::cout << "Could not prepare SQL" << std::endl;
sqlite3_close(db);
//system("pause");
return 0;
}
while (sqlite3_step(res) == SQLITE_ROW){
std::cout << "Name: " << sqlite3_column_text(res,0) << std::endl;
std::cout << "NUmber: " << sqlite3_column_text(res,1) << std::endl << std::endl;
}
sqlite3_finalize(res);
sqlite3_close(db);
//system("pause");
return 0;
}
This is the line that compiles the code:
g++ "-LD:\SQLite3\lib" -o sqliteTest00.exe main.o -lsqlite3 which include the lsqlite3. But when I build the project I will get the undefined reference to 'sqlite3_open" as well for 'sqlite3_close' and 'sqlite3_prepare_v2' and the rest of 'sqlite3_ commands. Any idea what is the problem with this file or linker?
Here is my code-
DBClientBase *conn = NULL;
string err_msg;
ConnectionString cs = ConnectionString::parse(connString, err_msg);
if (!cs.isValid()) {
throw "bad: " + err_msg;
}
try {
conn = cs.connect(err_msg);
}
catch (DBException &e) {
cout << "caught " << err_msg << endl;
return 1;
}
if (!conn) {
cout << "Unable to connect to DB" << endl;
return 1;
}
I would expect MongoDB to throw exception in case DB is not reachable. However, I am finding that if (!conn) is getting satisfied.
Why
catch (DBException &e) {
cout << "caught " << err_msg << endl;
return 1;
}
block isn't working?
From the current trunk source, ConnectionString::connect only seems to throw an exception when the string itself was invalid (and you already know that it was not, from your first conditional statement).
It just returns a NULL pointer and sets errMsg in all other cases.
In your defence, I couldn't find this documented anywhere at all; a very basic example of connect was all I could locate.
string err_msg;
ConnectionString cs = ConnectionString::parse(connString, err_msg);
if (!cs.isValid()) {
throw "bad: " + err_msg;
}
DBClientBase* conn = cs.connect(err_msg);
if (!conn) {
cout << "Unable to connect to DB: " << err_msg << endl;
return 1;
}