There are generally two types of characters that are created to connect to a SQL Server database
- one is to log on with SQL authentication
- One is a Windows -authenticated
Steps:
- Reference Namespaces System.Date.SqlClient
- Declaring a connection method in a string
- Create A connection object
- Calling methods
Such as:
There are two ways in which SQL Server database connections
a ,//windows authentication Log on and open the database
define a variable to store a string that connects to the database
S Tring constr= " server=.; Integrated security=sspi;initial Catalog=cshardb ( database name )"
Second, //sql authentication method
define a variable to store the string
S Tring constr= " server=.; USER=SA;PWD=SA;DATABASE=PWD1";
instantiate the SQL connected object, and write the string parameter
S qlconnection mysqlcon=new SqlConnection (Constr);
Open Database
M Ysqlcon.open ();
To conserve system resources and improve system performance, it is best to close the connection when you are finished using the database.
in the The C # language, because of the existence of a GC , will release resources at some point in the future, it is not conclusive, and cannot determine when the process occurs, and when you forget to close the database, the using Statement ensures that objects are released as soon as they are launched, thus closing the database
such as mtsqlcon.colse();
use using to close a database
U Sing(mtsqlcon)
{
M Ysqlcon.open();
Conso le.writeline (" Open database successfully ");
}
C onsole.writeline (" database successful shutdown "); // when launched, the database shuts down automatically
U The Sing statement not only improves performance, it also achieves the ability to shut down the database, and a try ... .. . Catch ... .. the. Finally statement controls the shutdown of the connection database to improve performance
through try... Catch ... .. . Finally
T Try
{
M Tsqlcon.open();
C onsole.writeline("Database is open");
}
C Atch
{
}
F inally
{
M ysqlcon.close();
Console . WriteLine("The database has been successfully closed");
}
Connection connecting, shutting down the database