Spent the early morning time, finally connected to my local database, I think it should be remembered!
Put a code First:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 7 usingSystem.Data.SqlClient;8 9 namespaceConsoleApplication1Ten { One class Program A { - Static voidMain (string[] args) - { the stringConnectionString =@"Data Source =.; I Nitial Catalog = Scott; - Integrated Security = True;";//There are two ways to do it ... - //string constr = "server=.; Database=scott;integrated Security=sspi "; - //SqlConnection connection = new SqlConnection (CONSTR); + -SqlConnection connection =NewSqlConnection (connectionString); + A stringQueryString ="SELECT ename,job,mgr from Dbo.emp;"; atSqlCommand Command =NewSqlCommand (queryString, connection); - connection. Open (); -SqlDataReader reader =command. ExecuteReader (); - while(reader. Read ()) - { -Console.WriteLine ("{0},{1},{2}", reader[0], reader[1],reader[2]); in } - Reader. Close (); to connection. Close (); + } - } the}
Connect to the database,
First, you add a namespace
Using System.Data.SqlClient;
If you connect to another database, each has a different namespace
Second, use the connection class to establish a connection
The code is as follows:
string connectionString = @ "Data Source =.; I Nitial Catalog = scott;16 Integrated Security = True; "; There are two ways of doing this ... //string constr = "server=.; Database=scott;integrated Security=sspi "; //sqlconnection connection = new SqlConnection (CONSTR);
Here are two ways to build
The first method is the way the book is changed a little bit
The second is on the Internet.
Explain the first of the following:
Data Source =. Represents a connection to the SQL SEVER database on the local server
Initial Catalog = Scott represents the initial database directory, Scott built a database for me, and you have to replace it with your own
intergrated Security = True; Indicates connection logon authentication, using Windows authentication.
However, the default value of FALSE indicates that you want to specify the user name, password
As shown below
Integrated Security = False; User ID = sa; Password = sqlsql123321;
However, this method exposes the password and is therefore not used frequently.
Again, it's the writing of the query statement.
String queryString = "Select Ename,job,mgr from Dbo.emp;"; SqlCommand command = new SqlCommand (queryString, connection), connection. Open (); SqlDataReader reader = command. ExecuteReader ();
As above code: the first to create a string representing the statement to query, here is
SELECT Ename,job,mgr from Dbo.emp
The ***.emp behind shows one of their tables
Ename,job,mgr represents three columns in my table
This gives you the results of the query.
C # connection on SQL Server 2008 first time practice