Related knowledge:
- All of the previous examples, June is access to a specific database (SQL Server), so injected SqlConnection, SqlCommand, SqlDataReader, SqlDataAdapter and other class names added "SQL" prefix, and is subordinate to the System.Data.SqlClient namespace. This poses a huge problem for the portability of the code. If a database is replaced with Oracle, MySQL, or BD2, the code is almost completely rewritten, which is very detrimental to reuse.
- The System.Data.Common namespace provides a set of classes and operations that allow a program to ignore the differences in the underlying database and make a unified call
- DbProviderFactories: represents all data providers
- DbProviderFactory: Represents a specific data provider, for example: System.Data.SqlClient
- DbConnection, DbCommand, DbDataReader: Object types unrelated to database implementation
- Using universal database access can make data access code independent of the database to a large extent
Main code:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 usingSystem.Data;7 usingSystem.Data.Common;8 9 namespaceConsoleApplication16Ten { One class Program A { - Const stringProvider ="System.Data.SqlClient"; - Const stringstrconn =@"Server=joe-pc;database=accountdbforsqlinjection;uid=sa;pwd=root"; the - Static voidMain (string[] args) - { - //get the data provider factory class +DbProviderFactory factory =dbproviderfactories.getfactory (provider); - + //creating a Connection object from a factory ADbConnection conn =Factory. CreateConnection (); atConn. ConnectionString =strconn; - - //Creating a Command object from a factory -DbCommand cmd =Factory. CreateCommand (); -Cmd. Connection =Conn; -Cmd.commandtext ="SELECT AccountID, AccountName, password from account"; in - Try to { + Conn. Open (); -DbDataReader dr =cmd. ExecuteReader (); the * while(Dr. Read ()) $ {Panax NotoginsengConsole.WriteLine ("{0}:{1},{2}", dr[0], dr[1], dr[2]); - } the } + Catch(Exception e) A { the Console.WriteLine (e); + } - finally $ { $ Conn. Close (); - } - } the } -}
ADO. NET notes--using universal data access