2012-09-20

C# and PHP database connection code comparison

Here, I’m trying to provide the equivalent DB connectivity code in C# and PHP. Let’s say the PHP code is as below,

<?php

mysql_connect('server.url.goes.here.com', 'username_goes_here', 'password_goes_here');
mysql_select_db('db_name_goes_here');

$q = 'SELECT * FROM myTable';
$r = mysql_query($q);

while (mysql_fetch_object($r)) {
        // do stuff
}

?>

The equivalent C# code would be like below

SqlConnection connection;
SqlDataReader r;

try
{
string connectionString = @ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
connection = new SqlConnection(connectionString);
connection.Open();
string q = "SELECT * FROM myTable";

SqlCommand sqlComm = new SqlCommand(q, connection);
r = sqlComm.ExecuteReader();

while (r.Read()) {
    //do stuff
}
}
catch(Exception)
{}
finally
{
  r.Close();
  connection.Close();
}

To make it easier to understand, I will take chunk by chunk from the code of both languages and try to explain.

 

PHP code:

mysql_connect('server.url.goes.here.com', 'username_goes_here', 'password_goes_here');
mysql_select_db('db_name_goes_here');

C# code:

SqlConnection connection;

string connectionString = @ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
connection = new SqlConnection(connectionString);
connection.Open();

In asp.net, Username and Password for the Database server, IP address/URL for the database sever and DB name are storing in the web.config file under connectionStrings section.

 

PHP code:

$q = 'SELECT * FROM myTable';

C# code:

string q = "SELECT * FROM myTable";

That’s how actually we declare variables in those languages. There is no relevant for DB. Above shows just how we store the strings in both languages.

 

PHP code:

$r = mysql_query($q);

C# code:

SqlCommand sqlComm = new SqlCommand(q, connection);
SqlDataReader r = sqlComm.ExecuteReader();

That’s how we execute the SQL query and store the result in a reader object. In C#, we use SqlDataReader object. In PHP we can directly execute the string representation of the SQL query. In C#, we have to build a SqlCommand object from the string representation of the SQL query.

 

PHP code:

while (mysql_fetch_object($r)) {
        // do stuff
}

C# code:

while (r.Read()) {
    //do stuff
}

That’s how we read the data from the reader objects.

No comments: