1. Create a new C # Console Application
2. go to Server Explorer, right-click Add Connection at Data connection (PIC1), enter the server name and database name (sometimes the server name does not appear in the dropdown box, you can go to SQL Server Management Studio Pic2 in the black bar), point out the test connection, if it fails, you need to see if the service is started
3. Write the following code in the program to run
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Data.SqlClient;namespacelinksqlconsole{classProgram {Static voidMain (string[] args) {SqlConnection conn=NewSqlConnection (); Conn. ConnectionString="Connection String";//See figure Pic3Conn. Open (); SqlCommand cmd=NewSqlCommand (); Cmd. Connection=Conn; Cmd.commandtext="SQL statements";//SELECT * FROM table namecmd. ExecuteNonQuery (); SqlDataReader SqlDataReader=cmd. ExecuteReader (); while(Sqldatareader.read ()) {stringStuid = sqldatareader.getstring (0); stringStuname = sqldatareader.getstring (1); intAge = Sqldatareader.getint32 (2); Console.WriteLine (Stuid+" "+ Stuname +" "+Age ); } sqldatareader.close (); Conn. Close (); } }}
Pic1
Pic2
Pic3
C # Connecting SQL Server Simple Tutorial