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