Connecting Visual c++ 2008 to MySql - 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.

Related

Connecting to a MySQL database with an ESP8266WiFi chip

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;

Connect Processing with SQL database and Get name of columns

I have connect Processing and SQL by using database library "de.Bezier.data.sql".
I don't know How can I get the name of columns in a specific Table.
I get the correct name of database, but i got the following as result of name of columns "Tables_in_sql7363100"
import de.bezier.data.sql.*;
MySQL sql;
String[] tableNames;
String[] columnNames;
void setup() {
size(300, 300);
database_connection();
if (connect) {
tableNames = sql.getTableNames();
for (int i=0; i<tableNames.length; i++) {
println(tableNames[i]);
}
columnNames = sql.getColumnNames();
for (int i=0; i<ColumnNames.length; i++) {
println(columnNames[i]);
}
}
}
void draw() {
background(255);
}
void database_connection() {
sql = new MySQL(this, "ServerName", "DataBase", "DUN", "PW");
if (sql.connect()) {
connect = true;
connect_status = "Conected";
} else {
connect = false;
connect_status = "Connection Failed";
}
}
There are 2 problems with what I'm seeing. The first one, which interests you, is that you didn't select any table. That's why you don't get a list of columns. You can fix this by using a simple query:
sql.query("SELECT * FROM myTable");
But that's not the only thing: you're not accounting for lag. It may work for now on a local database because lag is really low, but this won't fly with something which is over the internet. Here's an example where I show columns from a public test database and how long it takes to get the result from my query back:
import de.bezier.data.sql.*;
MySQL sql;
String user = "rfamro";
String pass = "";
String server = "mysql-rfam-public.ebi.ac.uk:4497";
String database = "Rfam";
String[] columnNames;
void setup() {
size(300, 300);
sql = new MySQL(this, server, database, user, pass);
}
void draw() {
if (columnNames != null) {
println("It took " + millis() + "ms to get this data back.");
for (String s : columnNames) {
println(s);
}
noLoop();
} else if (sql.connect()) {
sql.query("SELECT * FROM family");
sql.next(); // only use .next when you know you have data
columnNames = sql.getColumnNames();
}
}
From here, it takes between 2-7 seconds to get the data back. You'll understand that, the setup() method running taking about a couple milliseconds, you won't have any results back by then.
Hope this helps. Have fun!

Why JavaFX stucks when running a process?

I am building an application using JavaFX. Application does some CRUD operations with the MySQL Database. So currently, I have 2 functions.
User Registration.
Email Validation (Check if email already exists in the database).
User registration is called in a JFoenix Button event. When it clicked it is calling separate 3 functions in another class as follows,
public static int insertUser(User user) {
int status = 0;
try {
Connection con = DbConnection.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO users (name, password, email, country) VALUES (?, ?, ?, ?)");
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
ps.setString(4, user.getCountry());
status = ps.executeUpdate();
con.close();
}catch(Exception ex) {
ex.printStackTrace();
}
return status;
}
public static int updateTime(String email, String timestamp) {
int status = 0;
try {
Connection con = DbConnection.getConnection();
PreparedStatement ps = con.prepareStatement("UPDATE users SET timestamp = ? WHERE email = ?");
ps.setString(1, timestamp);
ps.setString(2, email);
status = ps.executeUpdate();
con.close();
}catch(Exception ex) {
ex.printStackTrace();
}
return status;
}
The problem is when I click the Button I see it is getting stuck while running that process. So I put that code inside the following,
Platform.runLater(() -> {
try {
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
});
Now it is somewhat okay but I see it is getting a little stuck after clicking (Ripple effect is not working well and also the mouse hover effect is not working as usual).
And Email Validation is done when the user types an email in the text field and the key released event is triggered and it is checking for the database result. The code for checking email is as follows,
public static boolean emailAvailability(String email) {
boolean status = false;
try {
Connection con = DbConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT email FROM users WHERE email = ?");
ps.setString(1, email);
ResultSet rs = ps.executeQuery();
status = rs.next();
con.close();
}catch(Exception ex) {
ex.printStackTrace();
}
return status;
}
In the key event also it is getting stuck more. Can't type a character for some milliseconds.
I don't see any issue with my code because I have done this many times with Java Swing and all are perfectly working fine in Swing. And if a button is getting stuck with the running process I just put those codes inside the following and it works perfect,
new Thread(new Runnable() {
public void run() {
}
}).start();
I am not going to or trying to compare Java Swing and JavaFX But I need to know why JavaFX is behaving like this? What should I do to avoid this and run the program smoothly with the CSS effects if it is a huge process or not? Really appreciate it if anybody can help me. Thanks in advance.
UPDATE
Here is my signUp code. Executes when button clicks,
private void signUp(ActionEvent event) {
if (name.getText.equals("") && name.getText().isEmpty()) {
if (!name.getStyleClass().contains("error-class")) {
name.getStyleClass().add("error-class");
nameImageValidation.setImage(new Image("danger.png"));
nameImageValidation.setVisible(true);
}
} else {
name.getStyleClass().removeIf(style -> style.equals("error-class"));
nameImageValidation.setVisible(false);
}
if (password.getText.equals("") && password.getText().isEmpty()) {
if (!password.getStyleClass().contains("error-class")) {
password.getStyleClass().add("error-class");
passwordImageValidation.setImage(new Image("danger.png"));
passwordImageValidation.setVisible(false);
}
} else {
password.getStyleClass().removeIf(style -> style.equals("error-class"));
passwordImageValidation.setVisible(false);
}
if (email.getText.equals("") && email.getText().isEmpty()) {
if (!email.getStyleClass().contains("error-class")) {
email.getStyleClass().add("error-class");
emailImageValidation.setImage(new Image("danger.png"));
emailImageValidation.setVisible(false);
}
} else {
email.getStyleClass().removeIf(style -> style.equals("error-class"));
emailImageValidation.setVisible(false);
}
if (country.getText.equals("") && country.getText().isEmpty()) {
if (!country.getStyleClass().contains("error-class")) {
country.getStyleClass().add("error-class");
countryImageValidation.setImage(new Image("danger.png"));
countryImageValidation.setVisible(false);
}
} else {
country.getStyleClass().removeIf(style -> style.equals("error-class"));
countryImageValidation.setVisible(false);
}
if(emailValidation() && passwordValidation() && fieldsValidation()) {
User user = new User(name.getText(), email.getText(), password.getText(), country.getText());
int insertStatus = UserController.insertUser(user);
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
if (insertStatus > 0) {
int updateStatus = UserController.updateTime(email.getText(), timestamp.toString());
if(updateStatus > 0) {
// Go to Login Page
} else {
showAlert(); // Error Message
}
} else {
showAlert(); // Error Message
}
} else {
showAlert(); // Error Message
}
}
Here the validateEmail code. Executes when user typing the email. Triggered when Key Released and when performing this after type a character have to wait some time and then appear next character and go...
private void validateEmail(KeyEvent event) {
boolean status = UserController.emailAvailability(email.getText());
if (!status) {
email.getStyleClass().removeIf(style -> style.equals("success-class"));
emailImageValidation.setImage(new Image("safe.png"));
emailImageValidation.setVisible(true);
} else {
email.getStyleClass().removeIf(style -> style.equals("error-class"));
emailImageValidation.setImage(new Image("danger.png"));
emailImageValidation.setVisible(true);
}
}
When you trigger a function from the GUI, execution happens in the main thread. Now, these calls are blocking, which means that until they return, the main thread can't update the GUI.
There are generally two ways to solve this:
Async functions, that yield (allows other code to run) until the resource they are waiting for become available
Threads, which means running part of the program in parrallel, which most likely will require you to think about locks etc.
I suggest you look into these two things, as they are quite central to making good apps that are connected to other services and IO

Insert int from class to database (mysql)

I have two classes, from which I want one int number (first code) inserted into a database. The only thing I found so far is with a prepared statement, but I want the int from "freeparking" inserted into the database (second code) every hour. I have prepared a sleep thread already, which lets my second code initiate every full hour. But I am not sure how to insert the integer with my database. Thanks for your help in advance!
private void setFreieparkplätze(int freeparking) {
this.freeparking = freeparking;
}
int freeparking = vehiclenumber.getParking();
}
static Connection connection = null;
static String databaseName = "";
static String url = "jdbc:mysql://localhost:3306/tiefgarage?autoReconnect=true&useSSL=false" + databaseName;
static String username = "";
static String password = "";
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(url, username, password);
**PreparedStatement ps = connection.prepareStatement("INSERT Into parkinglot(Numbers) VALUES (?)");** // ???
int status = ps.executeUpdate();
if (status != 0) {
System.out.println("Database connected");
System.out.println("Record was inserted");
}
I repeat my comment as answer to make it visible to anyone.
The query to add an integer in a db shoould be like:
INSERT Into parkinglot(Numbers) VALUES ("+ getFreeparking() +");
Note that Numbers (table column) has to be integer type and getFreeparking() is just a getter for freeparking int variable.

java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid cursor state while inserting values into database

the following code is a part of my application while executing this i am getting invalid cursor state error, i am using sql server 2005 and jsp and html.
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("Jdbc:Odbc:disman");
java.sql.Statement stmt = con.createStatement();
stmt.executeUpdate("insert into earthquake(area,rictor,eqz,kms,city,state,date1,time,population,carea,farea,pland,animals,humanlife,animalsloss,sinjury,mininjury)values('"+area+"','"+rictor+"','"+eqz+"','"+kms+"','"+city+"','"+state+"','"+date1+"','"+time+"','"+population+"','"+carea+"','"+farea+"','"+pland+"','"+animals+"','"+humanlife1+"','"+animalsloss1+"','"+sinjury1+"','"+mininjury1+"')");
String items[]=request.getParameterValues("cmbitem");
int i=0;
ResultSet rs1=stmt.executeQuery("select * from earthquake");
int eid=rs1.getInt("eid");
while(i < items.length)
{ String itm=items[i];
if(itm.equals("water bottle"))
{
int totallits=rempop*3;
int totalbottles=(int)(totallits/litperbottle);
stmt.executeUpdate("insert into eq_requirement(eid,items,noitems) values('"+eid+"','"+itm+"','"+totalbottles+"'");
i++;
break;
}
else if(itm.equals("nurses"))
{
int totaldoctors=(int)(sinjury/10);
totaldoctors=(int)(totaldoctors+(mininjury/20));
int totalnurses=totaldoctors*2;
stmt.executeUpdate("insert into eq_requirement(eid,items,noitems) values('"+eid+"','"+itm+"','"+totalnurses+"'");
i++;
break;
}
else
{
out.println("<script language=javascript>alert('Earth Quake Details not added');</script>");
}
}
out.println("<script language=javascript>alert('Earth Quake Details Added Successfully');</script>");
con.close();
}
catch(Exception e)
{
out.println(e);
}
}//if update==true
}//if post event
%>
Check your insert statements you miss the end braces ,
stmt.executeUpdate("insert into eq_requirement(eid,items,noitems)
values('"+eid+"','"+itm+"','"+totalbottles+"')");
And also here ,
stmt.executeUpdate("insert into eq_requirement(eid,items,noitems)
values('"+eid+"','"+itm+"','"+totalnurses+"')");
Update:
ResultSet rs1=stmt.executeQuery("select * from earthquake");
while(rs1.next){
int eid=rs1.getInt("eid");
}
Hope this helps
Side Note: Best way to avoid sql mistakes is printing your query before execution and also run them in the sql developer