search
HomeBackend DevelopmentC#.Net TutorialDetailed explanation of the usage of executenonquery

Detailed explanation of the usage of executenonquery

Detailed explanation of the usage of executenonquery

#Usage of ExecuteNonQuery for operating database technology in C

#Recently in I just need to catch up on the basic knowledge, and I just caught up on some database operation techniques in C#. Today I learned about ExecuteNonQuery. I looked at the code of my own project maintenance project and online data query. I basically understood the usage of ExecuteNonQuery. Let me make a brief summary. , for future reference.

The ExecuteNonQuery method is mainly used to update data, but of course it can also be used to perform target operations (such as querying the structure of the database or creating database objects such as tables). It is usually used to execute insert, update, and delete statements to change the data in the database without using Dataset. The select statement is not suitable for the ExecuteNonQuery() method.

Recommended "C Video Tutorial"

1. First, let’s take a look at the return value of ExecuteNonQuery:

1. For Update, If insert or Delete statements are executed successfully, the return value is the number of rows affected by the command. If the number of rows affected is 0, the return value is 0;

2. For all other types of statements, the return value is -1;

3. If a rollback occurs, the return value is also -1;

4. We generally judge whether the return value is greater than 0 for update operations. This is no problem. . But for other operations [such as operations on data structures (creating tables, etc.)] if the operation is successful, the return value is -1, but please pay attention. For example, adding a new table to the database, if the creation is successful, -1 will be returned. An exception will occur if it fails. It is best to use Try and Catch statements to catch exceptions when performing such operations.

2. The process of the command object updating the database through the ExecuteNonQuery method is very simple. The steps are as follows:

1. Create a database connection;

2. Create a Command object and specify a SQL Inser, Update, Delete query or stored procedure;

3. Attach the Command object to the database connection;

4. Call the ExecuteNonQuery() method;

5. Close the connection.

3. How to use the code example:

1. First is a very simple class, which provides how to use the command object to communicate with the new database through the ExecuteNonQuery method.

public class ExecuteNonQueryClas
    {
        private static string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;

        //as this method provided static method, set the constructor to priviate to prevent create instance with 'new ExecuteNonQuery()'
        private ExecuteNonQueryClas()
        {

        }

        public static int ExecuteNonQuery(string commandText)
        {
            return ExecuteNonQuery(commandText, (SqlParameter[])null);
        }

        public static int ExecuteNonQuery(string commandText,SqlParameter[] commandParams)
        {
            //if connectionString is null, then throw exception
            if(connectionString == null || connectionString.Length == 0)
                throw new ArgumentNullException("connectionString");
            
            using(SqlConnection conn = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand(commandText,conn);
                if (conn.State != ConnectionState.Open)
                    conn.Open();

                //check if the commandParams is not null, then attach params to command
                if(commandParams !=null)
                  AttachParameters(cmd,commandParams);

                int recordsAffected = cmd.ExecuteNonQuery();

                return recordsAffected;
            }

        }

        private static void AttachParameters(SqlCommand cmd,SqlParameter[] commandParams)
        {
            if (cmd == null) throw new ArgumentException("command");
            if (commandParams != null)
            {
                foreach (SqlParameter p in commandParams)
                {
                    if (p != null)
                    {
                        //// Check for derived output value with no value assigned
                        if ((p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input) && (p.Value == null))
                        {
                            p.Value = DBNull.Value;
                        }
                        cmd.Parameters.Add(p);
                    }
                }
            }
        }
    }

2. Call in the main function:

static void Main(string[] args)
        {
            string userName = Console.ReadLine();
            string loginId = "user";
            string sqlString = "update Users set UserName = @name where LoginID= @loginID";
            SqlParameter[] parms ={
                                      new SqlParameter("@name",userName),
                                      new SqlParameter("@loginID",loginId)
                                       
                                  };

            int rlt = ExecuteNonQueryClas.ExecuteNonQuery(sqlString,parms);

            Console.WriteLine(rlt);
            Console.Read();
        }

Okay, the above is the simplest introduction and example of using the ExecuteNonQuery method.

The above is the detailed content of Detailed explanation of the usage of executenonquery. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor