当前位置:网站首页>Self use learning notes - connected and non connected access to database

Self use learning notes - connected and non connected access to database

2022-04-23 17:10:00 Tomato Warrior


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;//sql
using System.Data;//ConnectionState
using System.Configuration;// Used to get the string in the configuration file 


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //----------
            string ConnStr = "server=(local);database=SystemCourse;integrated security=true";
           // string ConnStr = System.Configuration.ConfigurationManager
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = ConnStr;
            if(conn.State ==ConnectionState.Closed)
            conn.Open();
            //----------
            string sql = "select * from students";
            SqlCommand cmd = new SqlCommand(sql,conn);
           
            // establish Command After the object , You can execute SQL command , After execution, complete and close the data connection , The sample code is as follows .
            // cmd.ExecuteNonQuery(); // perform SQL command 
            //con.Close(); // Close the connection 
            //----------
            SqlDataReader reader = cmd.ExecuteReader();// take sql The statement is sent to sqlconnection, And produce a sqldatareader object 
            //reader Is read-only , Can't modify data ,reader Read one and release one , You can only move forward, not backward 
            while (reader.Read())
            {
                Console.WriteLine(" full name :{0}",reader[2].ToString());
            }
            reader.Close();
            if (conn.State == ConnectionState.Open)
            conn.Close();
        }
    }
}

版权声明
本文为[Tomato Warrior]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230553458195.html