自己初學C#,感覺從數據據庫獲取資料挺難的,有點恐俱感。雖然自己有點怕,但我還是努力去學!今天做了一個小程式--從數據庫中獲得資料輸出到控制台上。
using System.Data.SqlClient;
static void Main(string[] args)
{
#region 連接數據庫
SqlConnection dataConnection = new SqlConnection();
string userName = "sa";
string password = "sh2_123";
dataConnection.ConnectionString = "User ID=" + userName + ";Password=" + password +";Initial Catalog=Northwind;" + "Data Source=CCM02\\SQLEXPRESS";
dataConnection.Open();
#endregion
#region 執行語句
SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.CommandText = "select OrderID,OrderDate,ShippedDate,ShipName,ShipAddress,ShipCity,ShipCountry From Orders Where CustomerID='BLONP'";
SqlDataReader datareader = dataCommand.ExecuteReader();
#endregion
#region 輸出得到資料
while (datareader.Read())
{
#region 定義變量對應到欄位
int orderId = datareader.GetInt32(0);
DateTime orderDate = datareader.GetDateTime(1);
DateTime shipDate = datareader.GetDateTime(2);
string shipName = datareader.GetString(3);
string shipAddress = datareader.GetString(4);
string shipCity = datareader.GetString(5);
string shipCountry = datareader.GetString(6);
#endregion
Console.WriteLine(
"Order {0}\n placed {1} \n shipped {2} \n" +
"To Address {3} \n {4} \n {5} \n {6} \n\n",
orderId, orderDate, shipDate, shipName, shipAddress, shipCity, shipCountry);
}
#endregion
}
static void Main(string[] args)
{
#region 連接數據庫
SqlConnection dataConnection = new SqlConnection();
string userName = "sa";
string password = "sh2_123";
dataConnection.ConnectionString = "User ID=" + userName + ";Password=" + password +";Initial Catalog=Northwind;" + "Data Source=CCM02\\SQLEXPRESS";
dataConnection.Open();
#endregion
#region 執行語句
SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.CommandText = "select OrderID,OrderDate,ShippedDate,ShipName,ShipAddress,ShipCity,ShipCountry From Orders Where CustomerID='BLONP'";
SqlDataReader datareader = dataCommand.ExecuteReader();
#endregion
#region 輸出得到資料
while (datareader.Read())
{
#region 定義變量對應到欄位
int orderId = datareader.GetInt32(0);
DateTime orderDate = datareader.GetDateTime(1);
DateTime shipDate = datareader.GetDateTime(2);
string shipName = datareader.GetString(3);
string shipAddress = datareader.GetString(4);
string shipCity = datareader.GetString(5);
string shipCountry = datareader.GetString(6);
#endregion
Console.WriteLine(
"Order {0}\n placed {1} \n shipped {2} \n" +
"To Address {3} \n {4} \n {5} \n {6} \n\n",
orderId, orderDate, shipDate, shipName, shipAddress, shipCity, shipCountry);
}
#endregion
}