使用ADO.NET連接Microsoft SQL Azure Database 現(xiàn)在已經(jīng)變得非常容易,這篇文章提供一個示例控制臺程序來描述如何連接到Azure 的數(shù)據(jù)庫,中間還夾雜著幾個我認為連接Microsoft SQL Azure Database 的一些注意點。屬于SQL Azure入門級問題。呵呵,Azure達人可以繞過。
控制臺程序示例:
1.使用vs創(chuàng)建一個控制臺程序
2.將上述代碼中<ProvideUserName>替換為SQL Azure Database 登錄名,格式如login@server,如果你需要了解更多有關(guān)賬戶的信息可以查閱Managing Databases and Logins in SQL Azure一文。
3.替換<ProvidePassword>為你的賬戶密碼。
4.替換<ProvideServerName>為你的SQL Azure 服務(wù)器名,如servername.database.windows.net,與登陸格式‘@“符號后面部分應(yīng)該是一樣的。
5.<ProvideDatabaseName>即是你想用你的代碼創(chuàng)建的數(shù)據(jù)庫名(原來不存在的)。
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Microsoft.SDS.Samples
{
class Program
{
// Provide the following information
private static string userName = "<ProvideUserName>";
private static string password = "<ProvidePassword>";
private static string dataSource = "<ProvideServerName>";
private static string sampleDatabaseName = "<ProvideDatabaseName>";
static void Main(string[] args)
{
// Create a connection string for the master database
SqlConnectionStringBuilder connString1Builder;
connString1Builder = new SqlConnectionStringBuilder();
connString1Builder.DataSource = dataSource;
connString1Builder.InitialCatalog = "master";
connString1Builder.Encrypt = true;
connString1Builder.TrustServerCertificate = false;
connString1Builder.UserID = userName;
connString1Builder.Password = password;
// Create a connection string for the sample database
SqlConnectionStringBuilder connString2Builder;
connString2Builder = new SqlConnectionStringBuilder();
connString2Builder.DataSource = dataSource;
connString2Builder.InitialCatalog = sampleDatabaseName;
connString2Builder.Encrypt = true;
connString2Builder.TrustServerCertificate = false;
connString2Builder.UserID = userName;
connString2Builder.Password = password;
// Connect to the master database and create the sample database
using (SqlConnection conn = new SqlConnection(connString1Builder.ToString()))
{
using (SqlCommand command = conn.CreateCommand())
{
conn.Open();
// Create the sample database
string cmdText = String.Format("CREATE DATABASE {0}",
sampleDatabaseName);
command.CommandText = cmdText;
command.ExecuteNonQuery();
conn.Close();
}
}
// Connect to the sample database and perform various operations
using (SqlConnection conn = new SqlConnection(connString2Builder.ToString()))
{
using (SqlCommand command = conn.CreateCommand())
{
conn.Open();
// Create a table
command.CommandText = "CREATE TABLE T1(Col1 int primary key, Col2 varchar(20))";
command.ExecuteNonQuery();
// Insert sample records
command.CommandText = "INSERT INTO T1 (col1, col2) values (1, 'string 1'), (2, 'string 2'), (3, 'string 3')";
int rowsAdded = command.ExecuteNonQuery();
// Query the table and print the results
command.CommandText = "SELECT * FROM T1";
using (SqlDataReader reader = command.ExecuteReader())
{
// Loop over the results
while (reader.Read())
{
Console.WriteLine("Col1: {0}, Col2: {1}",
reader["Col1"].ToString().Trim(),
reader["Col2"].ToString().Trim());
}
}
// Update a record
command.CommandText = "UPDATE T1 SET Col2='string 1111' WHERE Col1=1";
command.ExecuteNonQuery();
// Delete a record
command.CommandText = "DELETE FROM T1 WHERE Col1=2";
command.ExecuteNonQuery();
// Query the table and print the results
Console.WriteLine("\nAfter update/delete the table has these records...");
command.CommandText = "SELECT * FROM T1";
using (SqlDataReader reader = command.ExecuteReader())
{
// Loop over the results
while (reader.Read())
{
Console.WriteLine("Col1: {0}, Col2: {1}",
reader["Col1"].ToString().Trim(),
reader["Col2"].ToString().Trim());
}
}
conn.Close();
}
}
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
}
}
}
現(xiàn)在我們來看看這段代碼干了些什么
1.首先,代碼使用SqlConnectionStringBuilder對象來連接SQL Azure Database的master數(shù)據(jù)庫,然后以sampleDatabaseName字符串值為名來創(chuàng)建一個數(shù)據(jù)庫
2.使用另一個SqlConnectionStringBuilder對象來連接到第一步創(chuàng)建的數(shù)據(jù)庫
3.一旦連接上SQL Azure Database 里面剛創(chuàng)建的數(shù)據(jù)庫,我們使用第二個SqlConnectionStringBuilder來創(chuàng)建數(shù)據(jù)庫表以及一些示例數(shù)據(jù)操作
4.最后,代碼在數(shù)據(jù)修改前和修改后返回數(shù)據(jù)到控制臺程序
如果大家想閱讀連接SQL Azure的一些具體細節(jié)信息,可以參閱Connecting to a Data Source (ADO.NET)
注意點:
通過以上的例子,我們已經(jīng)對連接SQL Azure有了一些基本認識,現(xiàn)在我們來討論一下這之間我們需要注意的一些小問題
為了避免遭受注入攻擊,我們使用SqlConnectionStringBuilder類,這也是.net framework框架自帶的類
我們需要很好的保護我們的連接字符串信息,如果讓別人知道了,他們可以使用我們的數(shù)據(jù)并且進行篡改等等一切毀滅性的損失
由于我們與SQL Azure通信過程中,這之間不知道要經(jīng)過多少個路由節(jié)點,為了保護我們的連接字符串不被別人盜用,所以我們最好設(shè)置ADO.NET Encrypt 和 TrustServerCertificate connection parameters,如代碼所示將Encrypt = True,TrustServerCertificate = False能夠確保我們的連接字符串得到加密,任何在通信中間攔截的人獲取了你的連接字符串也是沒有用的。