יום חמישי, 22 במרץ 2012

MySql Connection Flexibility




MySql הוא אחד ממסדי הנתונים הנחשבים בתעשייה ונהפך לסמל סטטוס, אין ספק שהוא אחד המובלים בתחום והיותו חינמי מאפשר לנו לבנות מאגרי מידע בעצמנו ביעילות ובמינימום הוצאות אבל זה לא נגמר בזה, היכולת שלו לעבוד על מערכות הפעלה שונות (Windows / Linux) מנחיתה מכת מוות ל Microsoft SQL שנמכר באלפי דולרים וכמובן שעובד על פלטפורמות Windows בלבד, לא באתי להלל אותו למרות שאולי צריך, אבל בהחלט היה פה מהפך, במאמר זה נעבור על ההתקנה של MySql ע"ג שרת Linux ואת דרכי התקשורות איתו ב 3 שפות :C ,C# ,Perl.

דרישות מקדימות:
שרת לינוקס - במקרה שלי Fedora.

התקנה:
#: yum install mysql  -  עבור התממשקות
#: yum install mysql-devel -  עבור התממשקות
#: perl -MCPAN- e "install DBD::mysql" - עבור התממשקות
#: yum install mysql-server

הקמה:
הפעלת ה Service:
#:service mysqld start

הגדרת סיסמא לשרת:
#:mysqladmin -u root password 'new-password'

התחברות לשרת:
#:mysql -u root -p

יצירת משתמש חדש:
mysql>CREATE USER root@'localhost' identified by 'new-password';

משהו קטן על הדרך - יצירת משתמש לחיבור מרוחק:
mysql>CREATE USER root@'%' identified by 'new-password';

נתינת הרשאות למשתמשים:
mysql> GRANT  alter, create, delete, drop, index, insert, select, 
            update on *.* to 'root'@'localhost';
יצירת Database חדש:
mysql> CREATE DATABASE db_new; 
יצירת טבלה חדשה:
mysql>CREATE TABLE example(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
 name VARCHAR(30),
 age INT)


בשלב זה אני יעצור עם ה Console כי אין לזה סוף אני ממליץ לעבוד עם אחד מ IDE's שקיימים בשוק ואם אתם לא מכירים ניתן להוריד את ה Workbench מאתר MySql , המאמר לא לא נוגע בכל הקשור לתחזוקה ונקודת המוצא היא שיש לכם רקע ב Sql ובשפות השונות, בעצם עד כאן הוא שלב בניית השרת עבור ההדגמה.

בכל צורות ההתחברות יש מכנה משותף,  האובייקטים שנעבוד איתם כמעט זהים בצורת העבודה ההבדל העיקרי הוא בשמות, ובכל שפה הם מוגדרים אחרת ודורשים ספריות אחרות אבל בגדול הם עושים אותו דבר, בחרתי דווקא בשפות אלו בגלל צורת השימוש , כלומר, שפת C נחשבת לשפה נמוכה , ואילו C# נחשבת לשפה עליונה ( ה Api עשיר יותר) ו Perl כשפת סקריפטים , בקיצור מגוון רחב של מימושים.

Connectors
לכל שפה יש את ה Connector שלה, שהוא בעצם ה Driver שמחבר אותנו למסד, באתר MySql תראו רשימה מרשימה של Connectors במגוון שפות ופלטפורמות, אנחנו נעבוד עם 3 צורות חיבור שונות , mysql-devel מכיל את כל קבצי ה Headers שאיתם נעבוד בשפת C , בעזרת ה Interface Module שנקרא DBI נעבוד עם Perl ובעזרת ה MySql.Data.dll נעבוד עם C#.

יאללה מספיק עם החרטה ונתחיל לכתוב!

Perl
Practical Extraction and Reporting Language היא שפת סקריפטים פופלרית מאוד וניתן להשתמש בה במערכות הפעלה שונות, סביבת הפיתוח שאני משתמש ב Perl נקראת Padre , אז כמו שאמרתי בהתחלה חייבים את המודול של DBD שהוא חלק מה DBI.


#!/usr/bin/perl

use DBI;
use DBD::mysql;


#Connection Parameters
$host = "localhost";
$database = "DataBaseName";
$tablename = "TableName";
$user = "UserName";
$pw = "PassWord";

my $dsn = 'dbi:mysql:DataBaseName:localhost:3306';

sub SendQuery($)
{
    $connect = DBI->connect($dsn, $user, $pw);
    my $sth = $connect->prepare($_[0]);
    $sth->execute();

    # Preview the return result of 
    while(@row = $sth->fetchrow_array()){
     print "$row[0]: $row[1] \n";  }
}

הפונקציה מאוד פשוטה, ככה זה בשפות סקריפטים.

#C
פה העסק כבר יותר מסובך וצריך מערך של פונקציות שבונים לנו שכבה בתוכנית שלנו שנקראת DAL - Data Access Layer , גם פה אסור לשכוח להוריד את ה Connector/.Net מאתר MySql, בנוסף נשתמש ב Class עזר שנקרא Api Response שמחזיר לנו את הנתונים, במקרה הזה ברור שנשתמש ב Visual Studio.


///---------------------------------------------DATA ACCESS LAYER---------------------------------
///---created by: Proxytype 17/3/2012 ------------------------------------------------------------------
///--- http://proxytype.blogspot.com ---------------------------------------------------------------------
///--- keep this info attach ----------------------------------------------------------------------THX------

using System;
using System.Collections.Generic;
using System.Web;
using MySql.Data.MySqlClient;

/// <summary>
/// DAL - Data Access Layer
/// </summary>
public class DAL
{

    MySqlConnection myconnection = new MySqlConnection("Server=127.0.0.1;
    Database= DataBaseName;Uid= UserName ;Pwd= PassWord ;charset=hebrew");
    MySqlCommand mycommand = new MySqlCommand();
    MySqlDataAdapter myadapter = new MySqlDataAdapter();

public DAL()
{
        //connecting the Command to the Connection
        mycommand.Connection = myconnection;
        //connecting the Adapter to the Command
        myadapter.SelectCommand = mycommand;
}

    /// <summary>
    /// execute query by sql statement
    /// </summary>
    /// <param name="sql">sql statement</param>
    /// <returns>api response of the operation</returns>
    public api_response execute_query(string sql)
    {
        //create new instance of api response
        api_response myresponse = new api_response();

        try
        {
            //attach the query command to the Command
            mycommand.CommandText = sql;
            myconnection.Open();
            mycommand.ExecuteNonQuery();

            myresponse.sucess = true;
         
        }
        catch (Exception ex)
        {
            myresponse.ex = ex.Message;
            myresponse.sucess = false;
        }
        finally
        {
            myconnection.Close();
            mycommand.CommandText = "";
        }

        //return api response for diagnose
        return myresponse;
    }

    /// <summary>
    /// execute query by sql statement using stored procedures
    /// </summary>
    /// <param name="sql">stored procedure name</param>
    /// <param name="myparam">parameter array for stored procedure</param>
    /// <returns>api response of the operation</returns>
    public api_response execute_query(string sql, MySqlParameter[] myparam)
    {
        //create new instance of api response
        api_response myresponse = new api_response();

        try
        {
            //adding the parameters to the Command
            for (int i = 0; i < myparam.Length; i++)
            { mycommand.Parameters.Add(myparam[i]); }

            //change command type of the Command
            mycommand.CommandType = System.Data.CommandType.StoredProcedure;
            mycommand.CommandText = sql;

            myconnection.Open();
            mycommand.ExecuteNonQuery();

            myresponse.sucess = true;
        }
        catch (Exception ex)
        {
            myresponse.sucess = false;
            myresponse.ex = ex.Message;
           
        }
        finally
        {
            myconnection.Close();

            //return the command type for text
            mycommand.CommandType = System.Data.CommandType.Text;
            mycommand.CommandText = "";
        }

        //return api response for diagnose
        return myresponse;
    }

    /// <summary>
    ///  execute scalar query by sql statement
    /// </summary>
    /// <param name="sql">sql statement</param>
    /// <returns>api response of the operation</returns>
    public api_response execute_scalar(string sql)
    {

        //create new instance of api response 
        api_response myresponse = new api_response();
        try
        {
            mycommand.CommandText = sql;
            myconnection.Open();

            //set the scalar object return from the execute
            myresponse.scalar_object = mycommand.ExecuteScalar();
            myresponse.sucess = true;

        }
        catch (Exception ex)
        {
            myresponse.ex = ex.Message;
            myresponse.sucess = false;
         
        }
        finally
        {
            myconnection.Close();
            mycommand.CommandText = "";
        }

        //return api response for diagnose
        return myresponse;
    }


    /// <summary>
    /// execute scalar query by sql statement using stored procedures
    /// </summary>
    /// <param name="sql">stored procedure name</param>
    /// <param name="myparam">parameter array for stored procedure</param>
    /// <returns>api response of the operation</returns>
    public api_response execute_scalar(string sql, MySqlParameter[] myparam)
    {
        //create new instance of api response
        api_response myresponse = new api_response();

        try
        {
            //adding the parameters to the Command
            for (int i = 0; i < myparam.Length; i++)
            { mycommand.Parameters.Add(myparam[i]); }

            //change command type of the Command
            mycommand.CommandType = System.Data.CommandType.StoredProcedure;
            mycommand.CommandText = sql;

            myconnection.Open();

            //set the scalar object return from the execute
            myresponse.scalar_object = mycommand.ExecuteScalar();
            myresponse.sucess = true;
       
        }
        catch (Exception ex)
        {
            myresponse.sucess = false;
            myresponse.ex = ex.Message;
        }
        finally
        {
            myconnection.Close();

            //return the command type for text
            mycommand.CommandType = System.Data.CommandType.Text;
            mycommand.CommandText = "";
        }

        //return api response for diagnose
        return myresponse;
    }


    /// <summary>
    /// return date by sql statement
    /// </summary>
    /// <param name="sql">sql statement</param>
    /// <returns>api response of the operation</returns>
    public api_response fill_adapter(string sql)
    {
        //create new instance of api response
        api_response myresponse = new api_response();

        try
        {
            //attach the query command to the Command
            mycommand.CommandText = sql;

            //set api response DataTable to the adapter for fill
            myadapter.Fill( myresponse.result_table);
            myresponse.sucess = true;
        }
        catch (Exception ex)
        {
            myresponse.sucess = false;
            myresponse.ex = ex.Message;
         
        }

        //return api response for diagnose
        return myresponse;
    }


    /// <summary>
    /// return date by sql statement using stored procedures
    /// </summary>
    /// <param name="sql">stored procedure name</param>
    /// <param name="myparam">parameter array for stored procedure</param>
    /// <returns>api response of the operation</returns>
    public api_response fill_adapter(string sql, MySqlParameter[] myparam)
    {
        //create new instance of api response
        api_response myresponse = new api_response();

        try
        {
            //adding the parameters to the Command
            for (int i = 0; i < myparam.Length; i++)
            { mycommand.Parameters.Add(myparam[i]); }

            //change command type of the Command
            mycommand.CommandType = System.Data.CommandType.StoredProcedure;
            mycommand.CommandText = sql;

            //set api response DataTable to the adapter for fill
            myadapter.Fill(myresponse.result_table);
        }
        catch (Exception ex)
        {
            myresponse.sucess = false;
            myresponse.ex = ex.Message;
        }
        finally
        {
            //return the command type for text
            mycommand.CommandType = System.Data.CommandType.Text;
            mycommand.CommandText = "";
        }

        //return api response for diagnose
        return myresponse;
    }
   
}

/// <summary>
/// api response object
/// </summary>
public class api_response
{
    public bool sucess;
    public string ex;
    public object scalar_object;
    public DataTable result_table = new DataTable();
}

///---------------------------------------------END COPY PASTE -----------------------------------

אז מה היה לנו פה? מערך של פונקציות לטיפול בסוגים שונים של שאילתות בשילוב Stored Procedure בנוסף אובייקט מרכזי שמנהל לנו את המידע ובקרה במקרה של תקלות, פשוט תעתיקו ותדביקו בפרוייקט שלכם, וקיבלתם DAL לעבודה שוטפת עם MySql.

C
התהליך ב C הוא קצת שונה, צריך להוריד את ה Headers של Mysql כמו שהסברתי בהתחלה, חשוב לי לציין שהקוד נוסה על מערכות לינוקס בלבד, יש פה גם קשר ישיר לסביבת העבודה, במקרה הזה הסביבה היא Eclipse ונעבוד מול MySql C API.

תחילה נגדיר מספר דברים בסביבה:

1. הגדרת ה Compiler 




2.הגדרת ה Linker



עכשיו אחרי ההכנות זה הזמן לכתוב הקוד:

//imported to keep this order 
#include <my_global.h>
#include <mysql.h>

void makequery(char * query)
{
 MYSQL *conn;
 
         //init the connection return ID 
         conn = mysql_init(NULL);
         
 if(conn == NULL){
  printf("Conn Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
     exit(1);
 }

 conn = mysql_real_connect(conn, "localhost", " UserName ", 
          " PassWord ", " DataBaseName ", 0, NULL, 0);

 if (conn == NULL) {
      printf("Real Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }


 if (mysql_query(conn,  query)) {
       printf("Query Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
       exit(1);
   }

 mysql_close(conn);

}

סיכום:
מה שניסיתי להדגים פה את הגמישות של MySql ובכלל להציג את היכולות שלו, זה היה באמת קצר...

ואוו...

יום שבת, 3 במרץ 2012

Arduino Starting Guide


מי שלא מכיר אז כדאי שיכיר מדובר בדבר החם ביותר שהאטלקים המציאו אחרי Ferrari, לוח קטן ופשוט שנועד במקור לעזור לתלמידים באלקטרוניקה אי שם באיטליה, הוא הפך לפופלרי בזכות הגדרתו כ Open Hardware ובעצם מאפשר לכל אחד לבנות אותו באיזו צורה שהוא רוצה וכמובן בעלות נמוכה , אפשר למצוא מגוון רחב של לוחות מבוססים על מעבד ATmega:



ניתן למצוא גרסאות מבוססות על ARM Cortex M3 32Bit.

מה אפשר לעשות איתו?

בגדול הוא בעיקר ללימוד ולמימוש קונספטים באלקטרוניקה ופיתוח עבור מערכות משובצות מחשב, ניתן לחבר אליו מגוון רכיבים כמו חיישנים, מנועים ואחסון ולדגום אותם בעזרת חיבור סיראלי (RS-232) , ניתן להלביש עליו רכיבים ייעודיים הנקראים Shields שלוקחים את ה Arduino צעד קדימה , מדובר על לוחות שמתלבשים כמו חליפה על חיבורי ה IO והחשמל שבלוח ומאפשרים לנו לעבוד על רכיבים קצת יותר מורכבים  כמו   GPS , BlueTooth, Wifi, Ethernet, LCD וכו'.



ניתן לחבר סוגים שונים של חיישנים כמו גז, תנועה, לחץ , זיהוי קול, אור והרשימה עוד הארוכה.




המפתחים של Arduino נתנו לנו סביבה חינמית לפיתוח שמבוססת על שפה שמזכירה מאוד את C אבל הרבה יותר פשוטה, לדוגמה כל תוכנית מתחילה עם הפונקציה Setup שבעצם מקבילה ל Init בשפות אחרות, נאתחל בה את הערכים בתוכנית , ואח"כ תרוץ הפונקציה Loop שהיא לולאה אינסופית שמטפלת ב IO.

int buttonPin = 2;

void setup()
{
  Serial.begin(57600);
  pinMode(buttonPin, INPUT);
}

void loop()
{
  // ...
}

התוכנית הראשונה שאני מדגים היא עבודה עם Led , התוכנית תתחבר ל Pin 13, שמוגדר כ  OnBoard Led, בנוסף נגדיר חיבור Serial על מנת להוציא הודעות למסך.

int ledPin = 13;             

void setup()
{
  pinMode(ledPin, OUTPUT);     
}

void loop()
{
  digitalWrite(ledPin, HIGH);   
  delay(1000);                 
  digitalWrite(ledPin, LOW); 
  delay(1000);                 
}


 אפשר להגיד שיש בלוח את כל הדברים שאנחנו צריכים: עבודה עם Type מגוונים כמו String, Float, Array , עבודה עם Interrupts , שעונים וכו' (לרשימת ה Reference המלאה לחץ כאן),  באמת לא חסכו , קיימים Libraries ייעודים לטיפול ב Servo , Serial, Android ועוד (לרשימה הרשמית לחץ כאן) , חינמי ו Open Source.

הסביבה עצמה מאוד פשוטה ונתנת להורדה מכאן בחינם,  היא מורכבת מסרגל כלים פשוט שמאפשר לעשות Compile לתוכנית להוריד אותה ללוח ולנטר אותה בעזרת חיבור Serial ,ששכחתי להגיד שהלוחות מגיעים עם חיבור Usb שגם מקור הכוח וגם מאפשר לנו לתקשר עם הלוח בעזרת חיבור Serial, וכמובן עורך טקסט צבעוני.



 Shell לצפיה בהודעות שחוזרות.


סיכום (איזו התרגשות!):

בהחלט מוצר נפלא שמאפשר לאנשים לא מנוסים לגעת בעולם האלקטרוניקה, כלי נהדר למימוש קונספטים בצורה זריזה וחסכונית ואפשר ללמוד ממנו המון, אין מה לומר מדובר בידידות חדשה, החלטתי לפתוח עבור הלוח הזה דף מרכזי בבלוג כי מדובר פה רק על ההתחלה ובעתיד אני אכתוב מאמרים נוספים בנושא ,אין ספק שהוא מרתק וזו הולכת להיות הרפתקה מטורפת ,אפשר לרכוש את הלוחות ברשת, מחיר ממוצע של Arduino Uno שהוא גרסה משופרת של Arduino Duemilanove הוא 100 ש"ח.

עכשיו תכלס איך זה נראה:


יאללה בלאגן...