Implementation of C accessing SQL Server database

  • 2021-08-12 03:19:59
  • OfStack

This paper describes the implementation method of C # accessing SQL Server database with an example. Share it for your reference. The details are as follows:

Here, we introduce using C # to access SQL Server database. There are several classes involved here: SqlConnection class, SqlCommand class, SqlDataReader class. The SqlConnection class is used to establish a connection with the database, the SqlCommand class is used to create the SQL command, and the SqlDataReader object is the result of executing the query statement that the SqlCommand object returns the result set.

Here's some of the code:

/* Among them server Represents the server, " . "Indicates the local server, 
DataBase Represents a database, uid Represents the user name of the connection, pwd Ratio denotation password */
string strDataBase = "Server=.;DataBase=Library;Uid=sa;pwd=123456;";
SqlConnection conn = new SqlConnection(strDataBase);
string sqlStatement = "select * from Reader";
SqlCommand sqlcmd = new SqlCommand(sqlStatement, conn); // Setting parameters 
SqlDataReader sdr = sqlcmd.ExecuteReader(); // Execute SQL Statement 
int cols = sdr.FieldCount; // Get the number of columns in the result row 
object[] values = new object[cols];
while (sdr.Read())
  sdr.GetValues(values); //values Save 1 Row data 
  for (int i = 0; i < values.Length; i++)
   Console.Write(values[i].ToString()+" ");

I hope this article is helpful to everyone's C # programming.

Related articles: