Reprint please indicate the source:
http://blog.csdn.net/gane_cheng/article/details/52233151
Http://www.ganecheng.tech/blog/52233151.html (better browsing effect)
Recently wanted to use C # to connect the SQL Server database, a search of information on the web, found that most of the LINQ. But I just want to simply connect the database, read the data, use the release of this connection, do not want to complete a heap of ORM class files to the project, after consulting the relevant information, summarized the following methods.
First you need to introduce the namespace in which the database connection resides.
Using System.Data.SqlClient;
Using System.Data;
You can then implement it in your code.
Generally we connect a database, need to know four things, the database server's IP address, database name, database username and password.
sqlconnection conn = null;
SqlDataReader dr = null;
SqlCommand com = null;
try {//Construct database connection string, use IP address, database name, username, password replace XXX string connstr= "server=x.x.x.x;database=xxx;user=xxx;pwd=xxx";
conn = new SqlConnection (CONNSTR); Conn.
Open ();
Write SQL statement String sqltext = "SELECT * FROM table";
com = new SqlCommand (SQLTEXT, conn); Dr = Com.
ExecuteReader (); if (Dr.
HasRows = = false) {return; } Dr.
Read (); MessageBox.Show (Dr[0].
ToString ()); The catch (System.Exception ex) {return;} finally {if (Dr!= null) {//Shut down SqlDataReader Dr.
Close (); } if (conn!= null) {//CLOSE database Conn.
Close (); }
}