C # uses SQL statements directly against database operations (CMD. ExecuteNonQuery)

Source: Internet
Author: User
Tags connectionstrings

Only introduction Read and delete

Regardless of the method used to manipulate the database is not open and the database connection problem, so we first add the connection field in app. Config

  <connectionStrings>    <add name="connstring" connectionstring= " server=.; database=chat;integrated security=true"/>  </connectionStrings>

The field is then read and needs to be System.Configuration.dll, so the DLL is added to the References.

When it comes to manipulating object lists, it's also necessary to add the corresponding entity classes.

So add the following class example

class UserAccount    {        publicstringgetset;}          Public string Get Set ; }            }

--------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------

OK, the text starts

Add a CS file and add the following code example

Very simple, not explained, in the comments are written

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Configuration;usingSystem.Data.SqlClient;namespacecmd_sqlquery{classTermsservice {stringconnstring = configurationmanager.connectionstrings["connstring"].        ToString (); /// <summary>        ///working with the database through SQL///Core/// </summary>        /// <param name= "SQL" >SQL statements</param>        /// <returns></returns>         Public intExecuteSQL (stringSQL) {SqlConnection conn=NewSqlConnection (connstring); SqlCommand cmd=NewSqlCommand (SQL, conn); Conn.            Open (); Try            {                intresult =cmd.                ExecuteNonQuery (); returnresult; }            Catch(Exception) {Throw; }            finally{Conn.            Close (); }        }        /// <summary>        ///splicing SQL statement call Addtermsvaule (String sql)///the process is stitching and calling/// </summary>        /// <param name= "Items" >incoming list of objects that need to be saved</param>         Public voidDb_additems (list<useraccount>Items) {            foreach(varIteminchItems) {StringBuilder Objstrbuilder=NewStringBuilder (); Objstrbuilder.append ("INSERT INTO UserAccount"); Objstrbuilder.append ("(ACCOUNT,PWD)"); Objstrbuilder.append ("Values (' {0} ', ' {1} ')"); stringsql =string. Format (objstrbuilder.tostring (), item. Account, item.                PWD); Console.setcursorposition (0,3); Console.Write ("Importing"); Console.foregroundcolor=consolecolor.red; Console.Write (Items.indexof (item)+1); Console.foregroundcolor=Consolecolor.gray; Console.WriteLine (" / "+items.count);            ExecuteSQL (SQL); }        }    }}

Invoking the example in the main function

 Static voidMain (string[] args) {Termsservice obj=NewTermsservice (); Console.WriteLine ("Preparing account Data ..."); List<UserAccount> items =NewList<useraccount> ();//prepare the object list             for(inti =0; I <5; i++) {items. ADD (NewUserAccount { account="ac--"+ (i +1). ToString (), PWD="pwd**"+ (i +1).            ToString ()}); } Console.WriteLine ("Prepared 5 peices of account data!"); Obj. Db_additems (items);//SaveConsole.WriteLine ("Press any key to truncate TABLE ...");            Console.readkey (); stringsql ="TRUNCATE TABLE UserAccount"; Obj. ExecuteSQL (SQL);//ClearConsole.WriteLine ("Press any key to exit ...");        Console.readkey (); }

Program:

C # uses SQL statements directly against database operations (CMD. ExecuteNonQuery)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.