Gokul's Blog

Code Snippet for SQL DB access

Leave a comment

// 1.  Create SQL Connection
SqlConnection conn = null;

// 2.  Create and open a connection object
conn = new SqlConnection("Connection String-refer Connectionstrings.com for syntax");

// 3.  Open the Connection
conn.Open();

// 4.  Create the SQL Command and assign it it a string
string strSQLCommand = "SELECT * FROM Mytable";

// 5.  Execute the SQL Command
SqlCommand command = new SqlCommand(strSQLCommand, conn);

// 6.  Use ExecuteScalar() to return the first result
string rv= (string)command.ExecuteScalar();

// 7.  Close the Connection
conn.Close();

// 8.  Return the Value
return rv;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s