C# development-operating database (15.6)

I. Overview

  • In the previous section C# Connection, we explained the method of C# language to connect to the database. After establishing a connection with the database, you can start to operate the objects in the database.

  • To operate the database, you need to use the properties and methods provided in the Command class. Here is how to use the Command class to manipulate the data in the data table

<!--more-->

Overview of the Command Class

Under the System.Data.SqlClient namespace, the corresponding Command class is SqlCommand, and the connection to the database must have been created before creating the SqlCommand instance.

2.1 Common construction methods

Construction method Description
SqlCommand() No-parameter construction method
SqlCommand(string commandText,SqlConnection conn) The construction method with parameters, the first parameter is the SQL statement to be executed, and the second parameter is the connection object of the database

2.2 Common attributes and methods

Operations on objects in the database include not only operations on data tables, but also operations on database objects such as databases, views, and stored procedures. Next, we will mainly introduce operations on data tables and stored procedures.

When operating on different database objects, the SqlCommand class provides different properties and methods. The commonly used properties and methods are shown in the following table

Attribute or method Description
CommandText Property, SQL statement to be executed in the Command object
Connection Properties, get or set the connection object of the database
CommandType Property, get or set the command type
Parameters Properties, set the parameters of the SQL statement in the Command object
ExecuteReader() Method to get the result of executing the query statement
ExecuteScalar() Method to return the value of the first row and the first column of the query result
ExecuteNonQuery() Methods to perform operations of adding, deleting, and modifying data tables

Three use the Command class to operate the database

  • Three command types are provided in the Command class, namely Text, TableDirect, and StoredProcedure, which are Text by default.

  • The so-called Text type refers to the form of using SQL statements, including SQL statements for adding, deleting, modifying and querying.

  • StoredProcedure is used to execute stored procedures; TableDirect is only valid in OLE DB drivers

  • You need to complete the following steps when using the Command class to operate the database

3.1 Create an instance of the SqlCommand class

There are two situations for creating an instance of the SqlCommand class, one is the command type is Text, the other is the command type is StoredProcedure.

3.1.1 The command type is Text

SqlCommand SqlCommand class instance name = new SqlCommand (SQL statement, instance of database connection class);

among them:

  • SQL statement: refers to the SQL statement to be executed by the instance of the SqlCommand class

  • The instance of the database connection class: refers to the instance created using the SqlConnection class, usually the instance of the database connection class is in an open state

3.1.2 The command type is StoredProcedure

SqlCommand SqlCommand class instance name = new SqlCommand (stored procedure name, instance of database connection class);

have to be aware of is:

  • The stored procedure must be a stored procedure in the current database instance, and when calling a stored procedure with parameters, you also need to add the corresponding stored procedure parameters in the instance of the SqlCommand class

To add parameters to the stored procedure, you need to use the Parameters property of the SqlCommand class instance to set the specific code as follows

SqlCommand class instance. Parameters.Add (parameter name, parameter value);

Here, the parameter name must be consistent with the parameter name defined in the stored procedure

3.2 Perform operations on the data table

When performing operations on data tables, there are usually two situations. One is to perform non-query SQL statements, that is, to add, modify, and delete operations, and the other is to perform query SQL statements.

3.2.1 Operations that perform non-query SQL statements

When executing a non-query SQL statement, you do not need to return the data in the table. You can directly use the ExecuteNonQuery method of the SqlCommand class. The return value of this method is an integer, which is used to return the data in the table after the SQL statement is executed by the SqlCommand class. Number of rows affected

When the return value of this method is -1, it means that the SQL statement failed to execute. When the return value of this method is 0, it means that the SQL statement has no effect on the data in the current data table.

For example, if you want to delete the information of the student whose student number is 1100, and the information of the student whose student number does not exist in the table, the SQL statement can be executed normally, but the number of rows affected in the table is 0

An instance of the SqlCommand class.ExecuteNonQuery();

It should be noted that if the executed SQL statement is executed incorrectly in the database, an exception will be generated, so this part requires exception handling

3.2.2 Execute the operation of the query statement

The query result is usually returned when the query statement is executed. The ExecuteReader method provided in the SqlCommand class returns a value of type SqlDataReader after executing the query SQL statement. The return value can be obtained by traversing the results in the SqlDataReader class.

The specific code is as follows

SqlDataReader dr = instance of the SqlCommand class.ExecuteReader();

In addition, if you do not need to return all the query results after executing the query statement, but only need to return a value, such as the number of rows in the query table, then you can use the ExecuteScalar method. The specific code is as follows.

int returnvalue = instance of the SqlCommand class.ExecuteScalar();

Five examples (see 15.5 for table creation)

5.1 Example 1: Make a user registration interface, use the SqlCommand class to add a record to the user information table

5.1.1 Effect picture

 

5.1.2 Code

  //"Register" button click event
  private void button1_Click(object sender, EventArgs e)
  {
      //Write database connection string
      string connStr = "Data Source=.;Initial Catalog=test;User ID=sa;Password=root";
      //Create an instance of SqlConnection
      SqlConnection conn = null;
      try
      {
          conn = new SqlConnection(connStr);
          //Open the database connection
          conn.Open();
          string sql = "insert into userinfo(name,password) values('{0}','{1}')";
          //Fill in the SQL statement
          sql = string.Format(sql, textBox1.Text, textBox2.Text);
          //Create SqlCommand object
          SqlCommand cmd = new SqlCommand(sql, conn);
          //Execute SQL statement
          int returnvalue = cmd.ExecuteNonQuery();
          //Determine whether the SQL statement is executed successfully
          if(returnvalue != -1)
          {
              MessageBox.Show("Registered successfully!");
          }
      }
      catch(Exception ex)
      {
          MessageBox.Show("Registration failed!"+ex.Message);
      }
      finally
      {
          if (conn != null)
          {
              //Close the database connection
              conn.Close();
          }
      }
  }

5.2 Example 2 Make a login interface, use the SqlCommand class to determine whether the user has logged in successfully

5.2.1 Effect picture

 

5.2.2 Code

  //"Login" button click event
  private void button1_Click(object sender, EventArgs e)
  {
      //Write database connection string
      string connStr = "Data Source=.;Initial Catalog=test;User ID=sa;Password=root";
      //Create an instance of SQLConnection
      SqlConnection conn = null;
      try
      {
          conn = new SqlConnection(connStr);
          //Open the database connection
          conn.Open();
          string sql = "Select count(*) from userinfo where name='{0}' and password='{1}'";
          //Fill in the SQL statement
          sql = string.Format(sql, textBox1.Text, textBox2.Text);
          //Create SqlCommand object
          SqlCommand cmd = new SqlCommand(sql, conn);
          //Execute SQL statement
          int returnvalue = (int)cmd.ExecuteScalar();
          //Determine whether the SQL statement is executed successfully
          if (returnvalue != 0)
          {
              MessageBox.Show("Login successful!");
          }
          else
          {
              MessageBox.Show("Login failed!");
          }
      }
      catch (Exception ex)
      {
          MessageBox.Show("Registration failed!" + ex.Message);
      }
      finally
      {
          if (conn != null)
          {
              //Close the database connection
              conn.Close();
          }
      }
  }
  //"Cancel" button click event
  private void button2_Click(object sender, EventArgs e)
  {
      this.Close();
  }

5.3 Example 3 Improve the user registration function to make the user name unique when registering

5.3.1 Effect picture

 

5.3.2 Code

  //"Register" button click event
  private void button1_Click(object sender, EventArgs e)
  {
      //Write database connection string
      string connStr = "Data Source=.;Initial Catalog=test;User ID=sa;Password=root";
      //Create an instance of SqlConnection
      SqlConnection conn = null;
      try
      {
          conn = new SqlConnection(connStr);
          //Open the database connection
          conn.Open();
          //Determine whether the username is repeated
          string checkNameSql = "select count(*) from userinfo where name='{0}'";
          checkNameSql = string.Format (checkNameSql, textBox1.Text);
          //Create SqlCommand object
          SqlCommand cmdCheckName = new SqlCommand(checkNameSql, conn);
          //Execute SQL statement
          int isRepeatName = (int)cmdCheckName.ExecuteScalar();
          if (isRepeatName != 0)
          {
              //If the user name is duplicated, the registration operation will not be performed
              MessageBox.Show("Username already exists!");
              return;
          }
          string sql = "insert into userinfo(name,password) values('{0}','{1}')";
          //Fill in the SQL statement
          sql = string.Format(sql, textBox1.Text, textBox2.Text);
          //Create SqlCommand object
          SqlCommand cmd = new SqlCommand(sql, conn);
          //Execute SQL statement
          int returnvalue = cmd.ExecuteNonQuery();
          //Determine whether the SQL statement is executed successfully
          if(returnvalue != -1)
          {
              MessageBox.Show("Registered successfully!");
          }
      }
      catch(Exception ex)
      {
          MessageBox.Show("Registration failed!"+ex.Message);
      }
      finally
      {
          if (conn != null)
          {
              //Close the database connection
              conn.Close();
          }
      }
  }

5.4 Example 4 Create a stored procedure to realize the user registration function, and use the SqlCommand class to call the stored procedure

5.4.1 Function analysis

The stored procedure of the user registration function is relatively simple. You only need to write a stored procedure with parameters to pass the user name and password to the stored procedure, and use the insert statement to add the user name and password to the user information table

5.4.2 Statement to create a stored procedure

存储过程Right-click on the database 添加存储过程, in dbo.Procedure.sql, fill in the stored procedure statement, and update

 

5.4.3 Code

//Write database connection string
string connStr = "Data Source=.;Initial Catalog=test;User ID=sa;Password=root";
//Create an instance of SqlConnection
SqlConnection conn = null;
try
{
    conn = new SqlConnection(connStr);
    //Open the database connection
    conn.Open();
    //Create SqlCommand object
    SqlCommand cmd = new SqlCommand("AddUser", conn);
    //Set the command type (CommandType) of the SQLCommand object to be a stored procedure
    cmd.CommandType = CommandType.StoredProcedure;
    //Set the parameters required by the stored procedure
    cmd.Parameters.AddWithValue("name", textBox1.Text);
    cmd.Parameters.AddWithValue("password", textBox2.Text);
    //Execute the stored procedure
    int returnvalue = cmd.ExecuteNonQuery();
    Console.WriteLine(returnvalue);
    //Determine whether the SQL statement is executed successfully
    if(returnvalue != -1)
    {
        MessageBox.Show("Registered successfully!");
    }
}
catch(Exception ex)
{
    MessageBox.Show("Registration failed!"+ex.Message);
}
finally
{
    if (conn != null)
    {
        //Close the database connection
        conn.Close();
    }
}

5.4.4 Description

Run the form, the effect is consistent with example 1. As can be seen from the above code, calling the stored procedure is not complicated, just change the value of the CommandType property in the SqlCommand object to StoredProcedure, and add the parameters needed in the stored procedure.

Guess you like

Origin blog.csdn.net/Calvin_zhou/article/details/108066237