void database::adduser(std::string username, std::string password, std::string land){
connect();
mysql_query(con, "USE users");
std::stringstream ss;
ss << "INSERT INTO users (username, paswd, land, landx, landy) VALUES (" << "'" << username << "'" << "," << "'" << password <<"'" << "," << "'" << land << "'"<< "50, 50)";
std::string insert;
insert = ss.str();
const char * c = insert.c_str();
mysql_query(con, c);
mysql_close(con);
}
int database::init(){
connect();
mysql_query(con, "USE users");
mysql_query(con, "CREATE TABLE IF NOT EXISTS users(username TEXT, passwd TEXT, land TEXT, landx INT, landy INT)");
mysql_close(con);
return 0;
}
char* database::getpaswd(std::string username){
connect();
mysql_query(con, "USE users");
std::stringstream ss;
ss << "SELECT paswd FROM users WHERE username=" << "'" << username << "'";
std::string insert;
insert = ss.str();
const char * c = insert.c_str();
mysql_query(con, c);
MYSQL_RES *result;
result = mysql_store_result(con);
MYSQL_ROW row;
row = mysql_fetch_row(result);
if(row == NULL){
std::cout << "NO USER OF THAT USERNAME" << std::endl;
return "NOT VALID USERNAME";
}
mysql_free_result(result);
mysql_close(con);
return row[0];
}
bool database::does_exist_user(std::string user){
connect();
mysql_query(con, "USE users");
std::stringstream ss;
ss << "SELECT username FROM users WHERE username=" << "'" << user << "'";
std::string insert;
insert = ss.str();
const char *c = insert.c_str();
mysql_query(con, c);
MYSQL_RES *result;
result = mysql_store_result(con);
MYSQL_ROW row;
row = mysql_fetch_row(result);
if(row == NULL){
mysql_free_result(result);
return false;
}
else{
mysql_free_result(result);
return true;
}
std::cout << "username taken" << std::endl;
return true;
}
void database::edit_land(std::string username, std::string land){
connect();
mysql_query(con, "USE users");
std::stringstream ss;
ss << "UPDATE users SET land=" << "'" << land << "' " << "WHERE username=" << "'" << username << "'";
std::string insert;
insert = ss.str();
const char *c = insert.c_str();
mysql_query(con, c);
mysql_close(con);
}
void database::edit_landX(std::string username, int land){
connect();
mysql_query(con, "USE users");
std::stringstream ss;
ss << "UPDATE users SET landx=" << land << " WHERE username=" << "'" << username << "'";
std::string insert;
insert = ss.str();
const char *c = insert.c_str();
mysql_query(con, c);
mysql_close(con);
}
void database::edit_landY(std::string username, int land){
connect();
mysql_query(con, "USE users");
std::stringstream ss;
ss << "UPDATE users SET landy=" << land << " WHERE username=" << "'" << username << "'";
std::string insert;
insert = ss.str();
const char *c = insert.c_str();
mysql_query(con, c);
mysql_close(con);
}
char* database::getland(std::string username){
connect();
mysql_query(con, "USE users");
std::stringstream ss;
ss << "SELECT land FROM users WHERE username=" << "'" << username << "'";
std::string insert;
insert = ss.str();
const char *c = insert.c_str();
mysql_query(con, c);
MYSQL_RES *result;
result = mysql_store_result(con);
MYSQL_ROW row;
row = mysql_fetch_row(result);
if(row == NULL){
return "ERROR";
}
mysql_close(con);
mysql_free_result(result);
return row[0];
}
char* database::getlandY(std::string username){
connect();
mysql_query(con, "USE users");
std::stringstream ss;
ss << "SELECT landy FROM users WHERE username=" << "'" << username << "'";
std::string insert;
insert = ss.str();
const char *c = insert.c_str();
mysql_query(con, c);
MYSQL_RES *result;
result = mysql_store_result(con);
MYSQL_ROW row;
row = mysql_fetch_row(result);
if(row == NULL){
std::cout << "ERROE ME BOI" << std::endl;
return "ERROR";
}
mysql_close(con);
mysql_free_result(result);
return row[0];
}
char* database::getlandX(std::string username){
connect();
mysql_query(con, "USE users");
std::stringstream ss;
ss << "SELECT landx FROM users WHERE username=" << "'" << username << "'";
std::string insert;
insert = ss.str();
const char *c = insert.c_str();
mysql_query(con, c);
MYSQL_RES *result;
result = mysql_store_result(con);
MYSQL_ROW row;
row = mysql_fetch_row(result);
if(row == NULL){
std::cout << "ERROE ME BOI" << std::endl;
return "ERROR";
}
mysql_close(con);
mysql_free_result(result);
return row[0];
}
void database::connect(){
con = mysql_init(NULL);
if(con == NULL){
std::cout << mysql_error(con) << std::endl;
exit(1);
}
if(mysql_real_connect(con, "127.0.0.1", "root", "password", "users", 3306, NULL, 0) == NULL){
std::cout << "NO BEUNO";
std::cout << mysql_error(con) << std::endl;
exit(1);
}
}
the issue is that I am unable to to use the create user function, but all of the other functions reading from the database work perfectly fine, so my question is why am i unable to use an insert statment in the program but am able to read from the database. It works on teh terminal whan i use mysql -u root -p to enter mysql on the terminal but when run it teh c++ code it does not work.
Related
#include <iostream>
#include <Windows.h>
#include "jdbc/mysql_connection.h"
#include "jdbc/cppconn/driver.h"
#include "jdbc/cppconn/exception.h"
#include "jdbc/cppconn/resultset.h"
#include "jdbc/cppconn/statement.h"
#include "jdbc/cppconn/prepared_statement.h"
#ifdef _DEBUG
#pragma comment(lib, "debug/mysqlcppconn.lib")
#else
#pragma comment(lib, "mysqlcppconn.lib")
#endif
using namespace std;
std::string Utf8ToMultiByte(std::string utf8_str);
int main()
{
try
{
sql::Driver* driver;
sql::Connection* connection;
sql::Statement* statement;
sql::ResultSet* resultset;
driver = get_driver_instance();
connection = driver->connect("tcp://127.0.0.1:3306", "root", "");
if (connection == nullptr)
{
cout << "connect failed" << endl;
exit(-1);
}
connection->setSchema("logindata");
statement = connection->createStatement();
resultset = statement->executeQuery("insert into new_table(number, id, wincount, totalgameplay) values(4, 132, 232349, 123)");
resultset = statement->executeQuery("select * from new_table ");
for (;resultset->next();)
{
cout << resultset->getInt("id") << " : " <<
Utf8ToMultiByte(resultset->getString("wincount")) << " : " <<
Utf8ToMultiByte(resultset->getString("totalgameplay")) << endl;
}
delete resultset;
delete statement;
delete connection;
}
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;
}
return 0;
}
std::string Utf8ToMultiByte(std::string utf8_str)
{
std::string resultString; char* pszIn = new char[utf8_str.length() + 1];
strncpy_s(pszIn, utf8_str.length() + 1, utf8_str.c_str(), utf8_str.length());
int nLenOfUni = 0, nLenOfANSI = 0; wchar_t* uni_wchar = NULL;
char* pszOut = NULL;
// 1. utf8 Length
if ((nLenOfUni = MultiByteToWideChar(CP_UTF8, 0, pszIn, (int)strlen(pszIn), NULL, 0)) <= 0)
return nullptr;
uni_wchar = new wchar_t[nLenOfUni + 1];
memset(uni_wchar, 0x00, sizeof(wchar_t)*(nLenOfUni + 1));
// 2. utf8 --> unicode
nLenOfUni = MultiByteToWideChar(CP_UTF8, 0, pszIn, (int)strlen(pszIn), uni_wchar, nLenOfUni);
// 3. ANSI(multibyte) Length
if ((nLenOfANSI = WideCharToMultiByte(CP_ACP, 0, uni_wchar, nLenOfUni, NULL, 0, NULL, NULL)) <= 0)
{
delete[] uni_wchar; return 0;
}
pszOut = new char[nLenOfANSI + 1];
memset(pszOut, 0x00, sizeof(char)*(nLenOfANSI + 1));
// 4. unicode --> ANSI(multibyte)
nLenOfANSI = WideCharToMultiByte(CP_ACP, 0, uni_wchar, nLenOfUni, pszOut, nLenOfANSI, NULL, NULL);
pszOut[nLenOfANSI] = 0;
resultString = pszOut;
delete[] uni_wchar;
delete[] pszOut;
return resultString;
}
why I cant get result of table information?
does insert and select then cout is not proper process?
Also I try with PrepareStatement with above the select phrase. But I worked properly
I know that preparestatement and createstatement is different with dynamic parsing and static parsing. what is more efficient with adding information to database?
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 ?
**``` c++ connect mysql
1.
Heading
#include <mysql/mysql.h>
#include <iostream>
#include<stdio.h>
#include <unistd.h>
using namespace std;
MYSQL *conn;MYSQL_RES *res;MYSQL_ROW row;
int main(int argc,char **argv)
{
const char *sever = "127.0.0.1"; //主机
const char *user = "root"; //用户名
const char *password = "root"; //用户密码
const char *database = "demo"; //数据库名称
conn = mysql_init(NULL);
if(!mysql_real_connect(conn,sever,user,password,database,3306,NULL,0))
{
cout << "connect error" << endl;
return 0;
}
mysql_set_character_set(conn,"utf8");
while(1==1){//where there not work
cout<<"enter while"<<endl;
sleep(2);
cout<<"link ok"<<endl;
if(mysql_query(conn,"select * from person"))
{
cout << "query error" << endl;
return 0;
}
//res = mysql_store_result(conn);
res = mysql_use_result(conn);
while((row = mysql_fetch_row(res)) != NULL)
{
cout << row[0] << '\t' << row[1] << '\t' << row[2] << '\t'
<< row[3] << '\t' << row[4] << endl;
}
cout<<"query end"<<endl;
}
mysql_free_result(res);
mysql_close(conn);
return 0;
}
```
it can show data from mysql.but why it not cycle.the while doesn't work?
i have tried many conform to explain this .but no any one can help my ,some one who can tell my why .
My Sqlite connector works just fine the first time I try to insert rows, but after it is closed and I run the program again it won't work at all.
Here is my constructor
Sqldatabase::Sqldatabase() {
open_connection("Database.db");
sqlite3_stmt *statement;
std::string sql = "SELECT id FROM articles ORDER BY id DESC LIMIT 1";
char *query = &sql[0];
if(sqlite3_prepare_v2(db, query, -1, &statement, 0) == SQLITE_OK && sqlite3_step(statement) == SQLITE_ROW) {
article_counter = sqlite3_column_int(statement, 0) + 1;
} else {
article_counter = 1;
}
}
Here is my preparedStatement method.
bool Sqldatabase::prepareStatement(std::string sql) {
char *query = &sql[0];
sqlite3_stmt *statement;
int result;
if (sqlite3_prepare_v2(db, query, sql.size(), &statement, 0) == SQLITE_OK) {
result = sqlite3_step(statement);
std::cout << sql << '\n';
sqlite3_finalize(statement);
if(result == SQLITE_DONE) {
return true;
}
}
std::cout << "SQL failed: " << sql << '\n';
return false;
}
And finally here is where I call the method.
bool Sqldatabase::create_ART(int ng_id, std::string title, std::string author, std::string text) {
//Creating article
std::ostringstream s;
s << "INSERT INTO articles (id, title, author, content, created) " <<
"VALUES (" << article_counter << ", '" << title << "', '" << author << "', '" << text << "' , CURRENT_DATE)";
std::string sql(s.str());
prepareStatement(sql);
//Adding article to newsgroup
std::ostringstream t;
t << "INSERT INTO contains VALUES ( " << article_counter << " , " << ng_id << ")";
std::string sql2(t.str());
article_counter++;
return prepareStatement(sql2);
}
My test script looks like this. And I already have a Newsgroup with id 1 in the database.
Sqldatabase db;
int main(int argc, char* argv[]){
std::cout << "-----Test of Memdatabase, Newsgroup and Article classes-----" << std::endl;
db = Sqldatabase();
db.create_ART(1, "Happy day", "John", "Sunday afternoon is pretty chill");
db.create_ART(1, "Chill day", "Peter", "Sunday afternoon is pretty chill");
}
Ah, you're trying to create a new record with the same id. ids are typically unique. try:
db.create_ART(2, "Chill day", "Peter", "Sunday afternoon is pretty chill");
I'm a new one used MYSQL.
The codes is:
void gdns_mysql::commit_task()
{
if (mysql_commit(conn) != 0)
{
throw_trackerr_str(boost::format("MysqlCommitError %d %s") % mysql_errno(conn) % mysql_error(conn));
}
}
This function commit_task is always spending 6~7 seconds.
I want to know why this happen ?
please list some reasons. Thank you
By the way:
The queries is like:
void gdns_mysql::update_server_status(std::string const& server_, std::string const& status_)
{
stringstream sql;
sql << "update server";
if (!status_.empty()) sql << " set status = '" << get_escape_string(status_) << "'";
else sql <<" set status = status_predict";
sql << " where serverip = '" << get_escape_string(server_) << "'"
<< endl;
execute(sql.str());
}
And
zone_ptrs_t gdns_mysql::query_zone_bykey(std::string const& zonename_)
{
string statement = "select * from zone";
bool where_flag = false;
if (!zonename_.empty())
{
statement += " where zonename = '" + get_escape_string(zonename_) + "'";
where_flag = true;
}
select(statement);
return fetch_datas<zone_t>();
}