使用ADO.NET連接Microsoft SQL Azure Database 現(xiàn)在已經(jīng)變得非常容易,這篇文章提供一個(gè)示例控制臺(tái)程序來(lái)描述如何連接到Azure 的數(shù)據(jù)庫(kù),中間還夾雜著幾個(gè)我認(rèn)為連接Microsoft SQL Azure Database 的一些注意點(diǎn)。屬于SQL Azure入門(mén)級(jí)問(wèn)題。呵呵,Azure達(dá)人可以繞過(guò)。
控制臺(tái)程序示例:
1.使用vs創(chuàng)建一個(gè)控制臺(tái)程序
2.將上述代碼中<ProvideUserName>替換為SQL Azure Database 登錄名,格式如login@server,如果你需要了解更多有關(guān)賬戶(hù)的信息可以查閱Managing Databases and Logins in SQL Azure一文。
3.替換<ProvidePassword>為你的賬戶(hù)密碼。
4.替換<ProvideServerName>為你的SQL Azure 服務(wù)器名,如servername.database.windows.net,與登陸格式‘@“符號(hào)后面部分應(yīng)該是一樣的。
5.<ProvideDatabaseName>即是你想用你的代碼創(chuàng)建的數(shù)據(jù)庫(kù)名(原來(lái)不存在的)。
代碼如下:
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)在我們來(lái)看看這段代碼干了些什么
1.首先,代碼使用SqlConnectionStringBuilder對(duì)象來(lái)連接SQL Azure Database的master數(shù)據(jù)庫(kù),然后以sampleDatabaseName字符串值為名來(lái)創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)
2.使用另一個(gè)SqlConnectionStringBuilder對(duì)象來(lái)連接到第一步創(chuàng)建的數(shù)據(jù)庫(kù)
3.一旦連接上SQL Azure Database 里面剛創(chuàng)建的數(shù)據(jù)庫(kù),我們使用第二個(gè)SqlConnectionStringBuilder來(lái)創(chuàng)建數(shù)據(jù)庫(kù)表以及一些示例數(shù)據(jù)操作
4.最后,代碼在數(shù)據(jù)修改前和修改后返回?cái)?shù)據(jù)到控制臺(tái)程序
如果大家想閱讀連接SQL Azure的一些具體細(xì)節(jié)信息,可以參閱Connecting to a Data Source (ADO.NET)
注意點(diǎn):
通過(guò)以上的例子,我們已經(jīng)對(duì)連接SQL Azure有了一些基本認(rèn)識(shí),現(xiàn)在我們來(lái)討論一下這之間我們需要注意的一些小問(wèn)題
為了避免遭受注入攻擊,我們使用SqlConnectionStringBuilder類(lèi),這也是.net framework框架自帶的類(lèi)
我們需要很好的保護(hù)我們的連接字符串信息,如果讓別人知道了,他們可以使用我們的數(shù)據(jù)并且進(jìn)行篡改等等一切毀滅性的損失
由于我們與SQL Azure通信過(guò)程中,這之間不知道要經(jīng)過(guò)多少個(gè)路由節(jié)點(diǎn),為了保護(hù)我們的連接字符串不被別人盜用,所以我們最好設(shè)置ADO.NET Encrypt 和 TrustServerCertificate connection parameters,如代碼所示將Encrypt = True,TrustServerCertificate = False能夠確保我們的連接字符串得到加密,任何在通信中間攔截的人獲取了你的連接字符串也是沒(méi)有用的。