Databases Reference
In-Depth Information
3.
Next, let's add a method to get a connection string. To demonstrate connecting to SQL
Database versus a local database, let's first connect to a local copy of the database. Then,
you will change the connection string to connect to a SQL Database instance. Below the
click event, add a new method called GetConString that returns the connection string for
your local instance of SQL Server. If you have a named instance, be sure to enter the server
name correctly (using the escape character). Here's the code to write:
string GetConString()
{
return "Server= server ;Database=AdventureWorks2012;User ID=sa;Password= password ;";
}
4.
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();
}
}
}
5.
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 Database. Instead of returning the connection string to
your local database, you want to return the ADO.NET connection string. Continue as follows:
6.
Back in your Visual Studio project, paste in the connection string you copied form the
Windows Azure Management Portal earlier in the GetConString method with the SQL
Database ADO.NET connection string, as shown in the following code. Be sure to enter
your correct password into the connection string:
string GetConString()
{
return "Server=tcp: servername .database.windows.net;Database=AdventureWorks2012;
UserID= username @ servername ;Password= password ;
Trusted_Connection=False;Encrypt=True;Connection Timeout=30";
}
 
Search WWH ::




Custom Search