Wednesday, July 22, 2020

inserting and reading of tables in mysql and c++

hi to all, I am showing you how to connect c++ and mysql  and writing to and retrieving of table from mysql.

You must install rpm file "mysql-connector-c++-1.1.4-linux-glibc2.5-x86-64bit.rpm" to connect C++ client to MySQL server.
code is :

#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <mysql/mysql.h>

using namespace std;

int main()
{
    //Here we are creating MYSQL object conn and initializing it with nullptr
    MYSQL *conn = nullptr;
    MYSQL_ROW row = NULL; // MYSQL row object
    MYSQL_RES *resultSet = nullptr; // MYSQL Resultset

    int qstate; // query status

//    Allocates or initializes a MYSQL object suitable for mysql_real_connect(). If conn is a NULL pointer,
//    the function allocates, initializes, and returns a new object. Otherwise, the object is initialized and the
//    address of the object is returned. If mysql_init() allocates a new object, it is freed when mysql_close() is called
//    to close the connection.

    conn = mysql_init(nullptr);
    if(conn)
    {
        cout << "Connection succeeded" << endl;
    }
    else
    {
        cout << " Connection failed" << mysql_error(conn) << endl;
    }
//    mysql_real_connect() attempts to establish a connection to a MySQL server running on host. Client programs must
//    successfully connect to a server before executing any other API functions that require a valid MYSQL connection handler structure.
    conn = mysql_real_connect(conn, "serverora.db.net","rahul", "rahul", "cbs", 3306,NULL,0);
    if(conn) // successfully connected
    {
        string prdname;

        int stck = 0;
        int rate = 0;
        int prdno = 0;
        cout << " Product name : ";

        getline(cin,prdname);
        cout << " current Stock : ";
        cin  >> stck;
        cout << " Rate : ";
        cin  >> rate;
        cout << " Product ID : " ;
        cin  >> prdno;

//      converting int to string

        string str1 = to_string(stck);
        string str2 = to_string(rate);
        string str3 = to_string(prdno);
//    our sql statement will be :-

        string sql = "insert into tableProductRecords(ProductName, Stock, Rate, ProductID) values('"
                      +prdname + "','"+ str1 +"','"+ str2 +"','"+ str3 +"');";

        qstate = mysql_query(conn, sql.c_str());// sql.c_str() converts string object to standard string
        if(!qstate) // if qstate is zero that is successfully executed
        {
            cout << " record updated";
        }
        else
        {
            cout << " error : " << mysql_error(conn) << endl;
        }



        sql = "select *from tableProductRecords"; // SQL to retrieve table contents

        qstate = mysql_query(conn, sql.c_str()); // executing query
        if(!qstate)
        {
            resultSet = mysql_store_result(conn); // taking result set from mysql server

            while(row = mysql_fetch_row(resultSet) ) // fetching row one by one
            {
                //displaying table rows one by one
                cout << " Product name : "<< row[0] << "  "  << " Stock : " << row[1] << " Rate : " << row[2] << " Product ID : " << row[3] << endl;
            }
        }
        else
        {
            cout << "QUERY NOT EXECUTED : " << mysql_error(conn);
        }

    }

    mysql_close(conn);

    return 0;
}

Sunday, July 5, 2020

how to connect perl with oracle

Here we will connect perl  with oracle.

Install & Configure Perl DBD for Oracle 11.2 on Centos linux.

Steps 1: Install Oracle 11.2 server/client on the hosts. I presume you have successfully installed Oracle 11gR2 in server side PC and Oracle instant client in client side PC.
You can download oracle from download.oracle.com

Steps 2: Install Perl on the host.
Check if perl is already installed on the host:

    # perl -v

Most hosts have perl already installed.
You can download and install perl from http://www.perl.org/get.html.
Step 3: Download PERL DBD-Oracle

Download link: http://search.cpan.org/~pythian/DBD-Oracle-1.44/
Just copy and paste in URL and download.
Step 4: unzip and untar the download DBD-Oracle

    [oracle@host1 tmp]$ gunzip DBD-Oracle-1.44.tar.gz
    [oracle@host1 tmp]$ tar -xvf DBD-Oracle-1.44.tar


Step 5: Create file oci.conf
Create file "oci.conf" at "/etc/ld.so.conf.d/" as root having entry of the location of Oracle LD_LIBRARY_PATH
For this example in mine oci.conf contains :-

"/opt/oracle/instantclient_11_2" of course without quotes.
then run following commands :-

    [root@host1 ~]$ more /etc/ld.so.conf.d/oci.conf
    output should be :- /opt/oracle/instantclient_11_2

    [root@host1 ld.so.conf.d]# ldconfig -v

What is ldconfig (from the man pages)
"DESCRIPTION: ldconfig  creates  the  necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib).  The cache is used by the run-time linker, ld.so or ld-linux.so.  ldconfig checks the header and filenames of the libraries it encounters when determining which versions should have their links updated."

Step 6: Install DBD-Oracle
Go to the directory where u untared the downloaded DBD-Oracle
Note: Make sure u have completed Step 5


    [root@host1 DBD-Oracle-1.44]# perl Makefile.PL -V 11.2.0
    [root@host1 DBD-Oracle-1.44]# make install

 Step 7: Test the install
Login back as Oracle user:
Create a script (dbd_oracle_test.pl) with the text below:

    #!/usr/bin/perl

    $host="serverora11gr2";
    $ora_listener="LISTENER";
    $oracle_sid="orcl";
    $listener_port="1521";
    $ora_user="scott";
    $ora_password="tiger";
    $db_table="emp";


    use DBI;
    use DBD::Oracle;


    my $dbh = DBI->connect("dbi:Oracle:host=$host;port=$listener_port;sid=$oracle_sid",$ora_user, $ora_password)
      or die "Error Connecting to Oracle : " . DBI->errstr;


    my $stm = $dbh->prepare("SELECT ename FROM $db_table")
      or die "Database Error: " . $dbh->errstr;


    $stm->execute()
      or die "Database Error: " . $sth->errstr;

    print "\n";
    while (( $ename ) = $stm->fetchrow_array() )
    { print "Employee name : $ename\n"; }


    print "\n";

    $stm->finish;


    $dbh->disconnect;


then run this  as :-

    $ perl dbd_oracle_test.pl

this will show this output:-

    Employee name : SMITH
    Employee name : ALLEN
    Employee name : WARD
    Employee name : JONES
    Employee name : MARTIN
    Employee name : BLAKE
    Employee name : CLARK
    Employee name : SCOTT
    Employee name : KING
    Employee name : TURNER
    Employee name : ADAMS
    Employee name : JAMES
    Employee name : FORD
    Employee name : MILLER

now its complete

complete menu driven programm in centos7.5 and codeblocks

complete menu driven program :-

file main.cpp :-
------------------

    #include "draw.h"
    #include "getchoice.h"


    using std::cin;
    using std::cout;

    char * menu[] ={
        "1.  Add New Product.",
        "2.  Add New Members.",
        "3.  View An Existing Product Records.",
        "4.  View An Existing Member's Record.",
        "5.  Billing.",
        "6.  Today's Sail.",
        "7.  Modify Product Record.",
        "8.  Modify Member's Record.",
        "9.  Instructions.",
        "10. Exit.",
        NULL
    };


    int main()
    {

        int choice = 0;
        clrscr();
        drawrect();
        FILE *input, *output;

        if (!isatty(fileno(stdout)))
        {
            fprintf(stderr,"You are not a terminal, OK.\n");
        }

        input = fopen("/dev/tty", "r");
        output = fopen("/dev/tty", "w");
        if(!input || !output)
        {
            fprintf(stderr,"Unable to open /dev/tty\n");
            exit(1);
        }

        do
        {
            choice = getchoice(menu, input, output);
            switch(choice)
            {
            case 1:
               func1(); break;
            case 2:
                func2(); break;
            case 3:
                func3(); break;
            case 4:
                func4(); break;
            case 5:
                func5();  break;
            case 6:
                func6(); break;
            case 7:
                func7(); break;
            case 8:
                func8(); break;
            case 9:
                func9(); break;
            case 10:
                clrscr();
                exit(0);
            }

        } while (choice != 0);
        return 0;
    }


file draw.h :-
----------------

    #ifndef DRAW_H_INCLUDED
    #define DRAW_H_INCLUDED

    #include <iostream>
    #include <cstdio>
    #include <sys/ioctl.h>
    #include <unistd.h>
    #include "draw.h"

    void gotoxy(int x,int y);
    void clrscr();
    void drawrect();

    #endif // DRAW_H_INCLUDED


file draw.cpp :-
------------------

    #include "draw.h"

    using std::cout;

    void gotoxy(int x,int y)
    {
        printf("%c[%d;%df",0x1B,y,x);
    }

    void clrscr()
    {
        gotoxy(0,0);

        struct winsize w;
        ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

        for (int x = 0; x < w.ws_row; x++)
        {
            for(int y = 0; y < w.ws_col; y++)
            {
                cout << " ";
            }
        }
        gotoxy(0, 0);
    }
    void drawrect()
    {
        winsize w;
        ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

        for(int i = 0; i <= w.ws_col; i++)
        {
            gotoxy(i, 2);
            cout << "-";

            gotoxy(i, w.ws_row);
            cout  << "-";
        }
        for ( int i = 2; i <= w.ws_row; i++)
        {
            gotoxy(1, i);
            cout << "|";
            gotoxy(w.ws_col, i);
            cout << "|";
        }
        gotoxy(0,0);
    }


file getchoice.h :-
---------------------

    #ifndef GETCHOICE_H_INCLUDED
    #define GETCHOICE_H_INCLUDED

    #include "draw.h"
    #include <cstdlib>
    #include <cstring>

    int getchoice(char *choices[], FILE *in, FILE *out);


    #endif // GETCHOICE_H_INCLUDED


file getchoice.cpp :-
------------------------

    #include "getchoice.h"

    using std::cout;
    using std::cin;

    int getchoice(char *choices[], FILE *in, FILE *out)
    {
        int chosen = 0;
        char **option, *ch, selection[3], choicechar;
        int i, j, k, l, m, len;

        char *p, *wp;

        ch = (char*)malloc(5);

    LABEL1: do {
            drawrect();

            gotoxy(25, 3);
            cout <<"MENU";
            gotoxy(23, 4);

            for( i = 23; i < 31; i++)
                cout << "-";

            l = 5;
            gotoxy(15, l);
            option = choices;
            l++;
            while(*option)
            {
                gotoxy(15, l);
                cout << *option;
                option++;
                l++;
            }

            gotoxy(15, ++l);
            cout << "Enter choice : ";

                ch = fgets(ch, 5, in);
                ch[strcspn(ch, "\r\n")] = '\0';
                m = atoi(ch);

            option = choices;

            j = 0;
            while(*option)
            {
                k = 0;
                while((choicechar = option[j][k]) != '.')
                {
                    selection[k] = choicechar;
                    k++;
                }
                selection[k] = '\0';
                if(m == atoi(selection))
                {
                    chosen = 1;
                    strcpy(ch, "");
                    break;
                }

                j++;

                if(option[j] == NULL)
                {
                    gotoxy(15, ++l);
                    cout << "Incorrect choice, select again";
                    cin.get();
                    clrscr();
                    goto LABEL1;
                    break;
                }
            }
        } while(!chosen);
      
        return m;
    }

output :-

how to code in Qt to file read and write.

hi, to  all, first of all I am showing you how to code in Qt to file read and write.

In this there are one plainTextEdit to display ( read from file content and display ) and write to file( from plaintext edit to file ), one lineEdit to take path for read file and display into plainTextEdit, and also to write from plainTextEdit to file given by path in lilneEdit.

There are two pushButtons "write" and "read" which performs write to file and  read from file as  given path  in lineEdit.

to do this :-

1. File-> New -> Application -> Qt Widgets Application ->choose.
2. give suitable path and title. Mine title is "qfiles".
3. kit selection  -> next -> class information -> mine is MyMainWindow-> next
4. project management -> finish.

now create a Ui (usert interface) as follows  <image ui>.

now in "mymainwindow.h"

#ifndef MYMAINWINDOW_H
#define MYMAINWINDOW_H

#include <QMainWindow>
#include <QTextStream>
#include <QFile>
#include <QDir>
#include <QMessageBox>
#include <QFileInfo>

namespace Ui {
class MyMainWindow;
}

class MyMainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MyMainWindow(QWidget *parent = 0);
    ~MyMainWindow();

private slots:
    void on_pushButtonWrite_clicked();

    void on_pushButtonRead_clicked();

private:
    Ui::MyMainWindow *ui;
    QFileInfo *checkfile;
    QFile *file;
};

#endif // MYMAINWINDOW_H


in mymainwindow.cpp

#include "mymainwindow.h"
#include "ui_mymainwindow.h"

MyMainWindow::MyMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MyMainWindow)
{
    ui->setupUi(this);
//    QFileInfo *checkfile = new QFileInfo;
    //QFileInfo *checkfile = nullptr;
    file = new QFile;
//    file = nullptr;
}

MyMainWindow::~MyMainWindow()
{
    delete ui;
}

void MyMainWindow::on_pushButtonWrite_clicked()
{
    QString filepath = ui->lineEditFile->text().trimmed();

    QDir d = QFileInfo(filepath).absoluteDir();
    QString absolute = d.absolutePath();
    //if(d.exists())
    if(!absolute.isEmpty())
    {
        file->setFileName(filepath);
        if(!file->open(QFile::WriteOnly | QFile::Text))
        {
             QMessageBox::information(this, "QDir", "the file  cannot be created");
        }

        else
        {
            QTextStream out(file);// = new QTextStream(file);
            QString str = ui->plainTextEdit->toPlainText();
            out << str;
            file->flush();
            file->close();

            QString name = QFileInfo(filepath).fileName();
            QMessageBox::information(this, "QFile", "File " + name +" has been written");
        }
    }
}

void MyMainWindow::on_pushButtonRead_clicked()
{
    QString filepath = ui->lineEditFile->text().trimmed();

    QDir d = QFileInfo(filepath).absoluteDir();
    QString absolute = d.absolutePath();
    //if(d.exists())
    if(!absolute.isEmpty())
    {
        file->setFileName(filepath);
        if(!file->open(QFile::ReadOnly | QFile::Text))
        {
             QMessageBox::information(this, "QDir", "the file  cannot be created");
        }

        else
        {
            QTextStream in(file);// = new QTextStream(file);
            QString text = in.readAll();
            ui->plainTextEdit->setPlainText(text);
            file->close();
        }
    }
}

now build and run this project :-

now  fill File path  and click on read pushbutton. If file path is valid then content of the text file will be displayed in plainTextEdit.
write some text in plainTextEdit and give file path, now content of plainTextEdit will be written in file as provided in file path  in lineEdit.