1 //2015/07/032 usingSystem;3 usingSystem.Collections.Generic;4 usingSystem.Linq;5 usingSystem.Text;6 usingSystem.Threading.Tasks;7 usingSystem.Data;8 usingSystem.Data.SqlClient;9 Ten namespaceado.netstart_1 One { A class Program - { - Static voidMain (string[] args) the { - //special string, database connection string - //First Kind - stringConnectionString ="server=.; database=booksample;uid=ljk;pwd=123456;"; + //The second Kind - //Windows Authentication + //when Windows authentication is used, Windows users are the users who run the program A //string connectionString = "server=.; Integrated security=true;database=booksample "; at - //classes used to access the database -SqlConnection connection =NewSqlConnection (connectionString); - - Try - { in //establish a connection to the database - connection. Open (); toConsole.WriteLine ("Connection already established"); + - //SQL is a string the stringsql ="INSERT into students (Id,stuname,phone,address,city,state) VALUES (7, ' AAA ', ' 1318697125 ', ' zz ', ' BB ', ' CCC ')"; * //SqlCommand represents the Send Database execution SQL command $SqlCommand Command =NewSqlCommand (sql,connection);Panax Notoginseng //Send command to database execution - //SQL statements can be divided into: query statements and non-query statements the + //The default work is under automatic transactions A //if work is under manual transaction the //BEGIN TRANSACTION + //Rollback/commit - $ //before executing SQL DML, start a transaction $SqlTransaction trans = connection. BeginTransaction ();//Transaction Object - - //set the transaction management to which the command belongs theCommand. Transaction =Trans; - Wuyi the intEffectcount =command. ExecuteNonQuery (); -Console.WriteLine ("{0} rows affected", effectcount); Wu -Console.Write ("the command has been executed and the transaction has not been committed, are you sure you want to commit? y/n"); About stringline =console.readline (); $ if(line. Substring (0,1). ToUpper () = ="Y") - { - trans.commit (); -Console.WriteLine ("transaction has been submitted"); A } + Else the { - Trans. Rollback (); $Console.WriteLine ("transaction has been rolled back"); the } the } the Catch(SqlException exception) the { - Console.WriteLine (Exception. Message); in } the finally the { About //or disconnect from the database the connection. Dispose (); the //connection. Close (); theConsole.WriteLine ("already disconnected"); + } - Console.readkey (); the }Bayi } the}
C # Two methods of accessing a database and two methods of transactions