• 從數據讀取資料方法


          自己初學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
            }
  • 相关阅读:
    程序员修炼之道读书笔记02
    程序员修炼之道读书笔记01
    2021年1月30日 体温上报app03(百度API的获取和配置方法)
    2021年1月28日 体温上报app02
    2021年1月27日 体温上报app01
    2021年1月26日 sqlite数据库
    2021年1月25日 列表与适配器
    16.CSS margin用法
    14.CSS 块级元素与行内元素
    12.CSS 简单认识margin
  • 原文地址:https://www.cnblogs.com/scottckt/p/800804.html
Copyright © 2020-2023  润新知