C#連接Sql Server數據庫並顯示在控制檯上

 1、使用SQL用戶名、密碼驗證

        Data Source = 服務器名;Initial Catalog = 數據庫名;User ID = 用戶名;Pwd = 密碼(沒有密碼可以省略)

                例如:public string connString = "Data Source=xp;Initial Catalog=student;User ID = 123;Pwd = 123";

 2、使用windows身份驗證

        Data Source = 服務器名;Initial Catalog = 數據庫名;Integrated Security = TRUE(或者:SSPI)

                例如:public string connString = "Data Source=xp;Initial Catalog=student;Integrated Security=TRUE";


首先添加using指令

using System.Data;

using System.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace sql_test
{
    class Program
    {
        static void Main(string[] args)
        {
            string connString = "Data Source=localhost;Initial Catalog=student;Integrated Security=TRUE";
            SqlConnection connection = new SqlConnection(connString);
            try
            {
                //打開數據庫  
                connection.Open();
                //Console.WriteLine("打開數據庫連接成功");
                string strqry="select * from student";
                SqlCommand cmd = new SqlCommand(strqry, connection);
                SqlDataReader dr;//創建DataReader對象  
                dr = cmd.ExecuteReader();//執行查詢  
                //if (dr.HasRows)  //判斷數據庫中是否含有數據
                //{
                //    Console.WriteLine("含有數據");
                //}
                while (dr.Read())
                {
                    Console.Write(dr["id"].ToString()+",");
                    Console.Write(dr[1].ToString() + ",");
                    Console.Write(dr[2].ToString() + ",");
                    Console.WriteLine(dr[3].ToString());
                }
                dr.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }  
           
            finally
            {
                //關閉數據庫  
                connection.Close();
            }
            Console.ReadLine();
           
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章