Database Reference
In-Depth Information
Making the Connection
Let's first look at how to connect to an Azure database using ADO.NET. Fire up an instance of Visual
Studio 2010, and create a new Windows Forms application. Then, follow these steps:
1.
Place a button on Form1, and double-click the new button to view its click
event.
2.
Before you place any code in the click event, let's add a method to get a
connection string. To demonstrate connecting to SQL Azure versus a local
database, let's first connect to a local copy of the database. Then, you can
change to connect to Azure. Below the click event, add a new method called
GetConString that returns the connection string for your local instance of SQL
Server. Here's the code to write:
string GetConString()
{
return "Server= server ;Database=TechBio;User ID=sa;Password= password ;";
}
Go back to the button's click event, and add the following code. This code calls
the GetConString method you previously added, returns the connection string,
establishes and opens a connection to the local database, and then closes the
connection:
private void button1_Click(object sender, EventArgs e)
{
string connStr = GetConString();
using (SqlConnection conn = new SqlConnection(connStr))
{
try
{
conn.Open();
MessageBox.Show("Connection made.");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
conn.Close();
}
}
}
3.
Run the application, and click the button on the form. You should get a
message box that says “Connection Made.”
Now, let's change this simple application to connect to SQL Azure. Instead of returning the
connection string to your local database, you want to return the ADO.NET connection string. Continue
as follows:
4.
Search WWH ::




Custom Search