C# 數據庫鏈接 Demo

c#數據庫操做Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {   //數據庫執行操做類 
        private SqlCommand cmd = null;
        //數據庫鏈接操做類 
        private SqlConnection mycon = null;  
        //鏈接參數
        private string conn = "Server=localhost ;Database=IntelligentCity_2015_GZ ;user id=sa;password=123456";
        //鏈接sql
        private string sql = "select * from ASM_ACCOUNT";
        static void Main(string[] args)
        {
            Program pr = new Program();
            pr.getConnected();      
        }
        //獲取鏈接
        private void getConnected()
        {
           
            try
            {
                mycon = new SqlConnection(conn);
                mycon.Open();
                //調用操做數據庫的方法,讀取數據庫中的數據
                operationDatabase(mycon);

            }catch(Exception e)
            {
                Console.WriteLine(e);
                Console.ReadKey();
            }finally
            {
                mycon.Close();
            }
            
        }
        //數據庫操做方法,讀取數據
        private void operationDatabase(SqlConnection conn )
        {
            cmd = new SqlCommand( sql,conn );
            //cmd.ExecuteNonQuery();
            SqlDataReader reader =  cmd.ExecuteReader();
            while(reader.Read())
            {
                Console.WriteLine("{0},{1}", reader["ACT_LOGIN_NAME"], reader["ACT_LOGIN_PASSWORD"]);
                Console.ReadKey();
            }
            reader.Close();
            
        }       
     }
 }
  • 操做結果

輸入圖片說明

相關文章
相關標籤/搜索