Not. Reservation för formatet för datasource och hur OraOLEDB.Oracle installeras. Har du Oracle finns det säkert hjälp. Open med extra tid (default 15s) <% Dim myConnection As SqlConnection *1 myConnection = New SqlConnection( "server=localhost;uid=sa;pwd=secret;database=my Data" ;Connect Timeout = 90 ) *2 myConnection.Open() *3 Läs/skriv mm. myConnection.Close() %> Öppna anslutning till DB. Mer S *2 Use Oracle’s.Net feature">

Presentation laddar. Vänta.

Presentation laddar. Vänta.

Databasanslutning TDS- Tabular Data Stream (SQL) OLE DB- Data som kan representeras som rad och kolumn ODBC- Open Data Base Connectivity (Data Source Name.

Liknande presentationer


En presentation över ämnet: "Databasanslutning TDS- Tabular Data Stream (SQL) OLE DB- Data som kan representeras som rad och kolumn ODBC- Open Data Base Connectivity (Data Source Name."— Presentationens avskrift:

1 Databasanslutning TDS- Tabular Data Stream (SQL) OLE DB- Data som kan representeras som rad och kolumn ODBC- Open Data Base Connectivity (Data Source Name DSN) ODBC databas MS SQL ExcelAccess OleDb provider for ODBC OleDb provider Jet TDS provider (SQL-Client) Hanteras direkt av CLR ODBC driver(DSN) VB,C#….. {ASP.NET-sida} Andra datakällor OleDb provider Exchange Prestanda MySQL, Textfil m.fl Oracle Eget ”NameSpace” ADO.NET

2 Access Open/Close <% Dim myConnection As OleDbConnection *1 Deklarationer myConnection = New OleDbConnection( "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=c:\inetpub\database\myData.mdb" ) *2 Dataförberedelser myConnection.Open() *3 Läs/skriv mm. myConnection.Close() %> SQL Open/Close <% Dim myConnection As SqlConnection *1 Deklarationer myConnection = New SqlConnection( "server=localhost;uid=sa;pwd=secret;database=my Data" ) *2 Dataförberedelser myConnection.Open() *3 Läs/skriv mm. myConnection.Close() %> Öppna anslutning till DB A*A* S*S* *? Platsreferens för senare bruk!

3 Oracle Open/Close <% Dim myConnection As OleDbConnection myConnection = New OleDbConnection ("Provider=OraOLEDB.Oracle; User Id=ORANET;Password=ORANET; Data Source=orcl9i.idc.oracle.com; OLEDB.NET=true”" ) myConnection.Open() Läs/skriv mm. myConnection.Close() %> Not. Reservation för formatet för datasource och hur OraOLEDB.Oracle installeras. Har du Oracle finns det säkert hjälp. Open med extra tid (default 15s) <% Dim myConnection As SqlConnection *1 myConnection = New SqlConnection( "server=localhost;uid=sa;pwd=secret;database=my Data" ;Connect Timeout = 90 ) *2 myConnection.Open() *3 Läs/skriv mm. myConnection.Close() %> Öppna anslutning till DB. Mer S *2 Use Oracle’s.Net feature

4 ODBC Open/Close <% Dim myConnection As OleDbConnection myConnection = New OleDbConnection( ”DSN=myDSN" ) myConnection.Open() Läs/skriv mm. myConnection.Close() %> Not. DSN (myDSN) måste skapas först med ODBC Data Source Administrator Fördel: DSN anslutningsinformation testa en gång, när den skapas. Den som skapar den har rättigheterna! ODBC-connector finns även bl.a för mySQL, textfil, excel m.fl. Öppna anslutning till DB. Ännu mer

5 ODBC Open Data Base Connectivity Using Data Sources (ODBC) Eget Kompendium

6 Access: Insert INTO ____ <% Dim myConnection As OleDbConnection Dim myCommand As OleDbCommand myConnection = New OleDbConnection( "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=c:\inetpub\database\myData.mdb" ) myCommand = New OleDbCommand( "Insert INTO testTable ( col1 ) Values ( ’Hello' )", myConnection ) myConnection.Open() myCommand.ExecuteNonQuery() myConnection.Close() %> SQL: Insert ____ <% Dim myConnection As SqlConnection Dim myCommand As SqlCommand myConnection = New SqlConnection( "server=localhost;uid=sa;pwd=secret;database=my Data" ) myCommand = New SqlCommand( "Insert testTable ( col1 ) Values ( 'Hello' )", myConnection ) myConnection.Open() myCommand.ExecuteNonQuery() myConnection.Close() %> Insert-command Insert-command INSERT tablename (column1, column2…) VALUES (value1, value2…)

7 Update: ACCESS UPDATE tablename SET column1 = value1, column2 = value2…WHERE sökuttryck <% Dim myConnection As OleDbConnection Dim myCommand As OleDbCommand myConnection = New OleDbConnection( "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=c:\inetpub\database\myData.mdb" ) myCommand= New OleDbCommand( "UPDATE testTable SET col1='hello’ WHERE col1='fred'", myConnection ) myConnection.Open() myCommand.ExecuteNonQuery() myConnection.Close() %>

8 Update: SQL UPDATE tablename SET column1 = value1, column2 = value2…WHERE sökuttryck <% Dim myConnection As SqlConnection Dim myCommand As SqlCommand myConnection = New SqlConnection("server=localhost;uid=sa;pwd=secret; database=myData” ) myCommand= New SqlCommand( "UPDATE testTable SET col1='hello’ WHERE col1='fred'", myConnection ) myConnection.Open() myCommand.ExecuteNonQuery(). myConnection.Close() %>

9 Update: SQL mer UPDATE tablename SET column1 = value1, column2 = value2…WHERE sökuttryck <% Dim myConnection As SqlConnection Dim myCommand As SqlCommand Dim recordsAffected As Integer myConnection = New SqlConnection("server=localhost;uid=sa;pwd=secret; database=myData” ) myCommand= New SqlCommand( "UPDATE testTable SET col1='hello’ WHERE col1='fred'", myConnection ) myConnection.Open() recordsAffected = myCommand.ExecuteNonQuery(). myConnection.Close() %>

10 Access DELETE FROM____WHERE SQL DELETE ____ WHERE Andra kommandon: SELECT column1, column2 FROM tablename1, tablename2 WHERE sökuttryck {SELECT * FROM tablename} Dim myDataReader As OleDbDataReader Dim myDataReader As SqlDataReader O.S.V. DELETE tablename WHERE sökuttryck

11 <% Dim myConnection As SqlConnection Dim myCommand As SqlCommand Dim myDataReader As SqlDataReader myConnection = New SqlConnection( "server=localhost;uid=sa;pwd=secret;pwd=secret;database=Pubs" ) myConnection.Open() myCommand = New SqlCommand( "Select * from Authors", myConnection ) myDataReader = myCommand.ExecuteReader() While myDataReader.Read() Response.Write( myDataReader.Item( "au_lname" ) ) End While myDataReader.Close() myConnection.Close() %> ’au_lname är en column i databasen (last name).Item-property konverterar värdet till ”lämplig”.NET datatyp SQL DataReader

12 <% Dim myConnection As SqlConnection Dim myCommand As SqlCommand Dim FirstName As String = "Robert” Dim LastName As String = "Johnson" myConnection = New SqlConnection( "server=localhost;uid=sa;pwd=secret;database=myData" ) myConnection.Open() myCommand = New SqlCommand( "Insert Authors ( FirstName, LastName ) )", myConnection ) myCommand.Parameters.Add( New SqlParameter( SqlDbType.Varchar, 30 )) myCommand.Parameters( ).Value = FirstName myCommand.Parameters.Add( New SqlParameter( SqlDbType.Varchar, 30 )) myCommand.Parameters( ).Value = LastName myCommand.ExecuteNonQuery() myConnection.Close() %> ’Parameter måste naturligtvis matcha platshållarens namn i SQL-satsen och börja Parametrar med SQL-Kommandon Platshållare Parametrar ger effektivare frågor och frågorna blir dynamiska. (Bättre exempel på bra kod finns i boken) Faktaruta

14 <% Dim myConnection As SqlConnection Dim myCommand As SqlCommand Dim FirstName As String = "Robert” Dim LastName As String = "Johnson" myConnection = New SqlConnection( "server=localhost;uid=sa;pwd=secret;database=myData" ) myConnection.Open() myCommand = New SqlCommand( "InsertAuthors", myConnection ) myCommand.CommandType = CommandType.StoredProcedure myCommand.Parameters.Add( New SqlParameter( SqlDbType.Varchar, 30 )) myCommand.Parameters( ).Value = FirstName myCommand.Parameters.Add( New SqlParameter( SqlDbType.Varchar, 30 )) myCommand.Parameters( ).Value = LastName myCommand.ExecuteNonQuery() myConnection.Close %> ’Istället för SQL-kommando så skickas namnet på en lagrad procedur "InsertAuthors” ’och sedan talar man också om vilken kommandotyp det är, och skickar parametrar. Lagrad procedur (Stored Procedure) till ADO.NET create procedure Varchar( 50 Varchar( 50 ) AS Insert Authors ( FirstName, LastName ) ) GO I Databasen !

16 Query Analyzer i MS SQL Här kan man se och även dra&släppa ”kolumner” mm. rakt in i Query’n

17 Lagrad procedur, knappa kod Här har jag min procedur från Query Analyzer Högerklick, New Stored Procedure

18 Lagrad procedur, knappa kod Det här är procedurens ”kör- kommando”. Det läggs till automatiskt när proceduren skapas När man väljer OK så skapas proceduren Här är det bara att knappa in kod

19 Lagrad procedur, Check Syntax Här sätter man vilka som ska få köra, oftast måste proceduren sparas först och sedan öppnas för editering innan Permissions kan sättas Test att man skrivit koden rätt, ingen test att det verkligen fungerar.

20 Lagrad procedur, Permissions

21 <% Dim myConnection As SqlConnection Dim myCommand As SqlCommand Dim myParam As SqlParameter myConnection = New SqlConnection( "server=localhost;uid=sa;pwd=secret;database=myData" ) myConnection.Open() myCommand = New SqlCommand( "getLastName", myConnection ) myCommand.CommandType = CommandType.StoredProcedure myParam = myCommand.Parameters.Add( New SqlParameter( "RETURN_VALUE", SqlDbType.INT )) myParam.Direction = ParameterDirection.ReturnValue myParam = myCommand.Parameters.Add( New SqlParameter( SqlDbType.Varchar, 50 )) myParam.Direction = ParameterDirection.Input myParam.Value = "Robert” myParam = myCommand.Parameters.Add( New SqlParameter( SqlDbType.Varchar, 50 )) myParam.Direction = ParameterDirection.Output myCommand.ExecuteNonQuery() If myCommand.Parameters( "RETURN_VALUE" ).Value Then Response.Write( "The last name is " & MyCommand.Parameters( ).Value ) Else Response.Write( "No author found!" ) END If myConnection.Close() %> UtParameter med SQL-Kommandon Det gamla vanliga Hur är detta möjligt? Svar i proceduren.

22 getLastName create procedure Varchar( 50 Varchar( 50 ) Output AS = LastName From Authors WHERE FirstName is Null Return( 0 ) ELSE Return( 1 ) I Databasen I ASP.NET: True = 1 / False = 0

23 ParameterDirection för Procedur VB/C# Input InputOutput Output ReturnValue ( Inte inputparameter ) SQL (T-SQL) ”inget” Output Return ( ) –VarChar –Money –Date –Int –… Return parameters can be of any data type except the text or image data types. ex. ReturnValue Integer – Return int

24 ”Måsten” Formulärdata ( Ska alltid valideras innan dom skickas) If isValid Then ”Spara data till DB” End If Före kod i Page –Option Explicit ON –Option Strict ON ex. Håller koll på att variabler har deklarerats. (Default = ON) Håller koll på datakonverteringar så att data inte förloras

25 Felhantering Alltid när du kontaktar system utanför. Exceptions try kod catch ex As Exception Hantera ”felet” finally Avsluta end try Fortsätt med koden. Om det går dåligt, hoppa ur till ”catch”. Flera ”nivåer” med Exceptions och hantering av dessa kan radas upp. Egna kan också skapas och hanteras.

26 Felhantering Alltid när du kontaktar system utanför. try kod (throw new DevideByZeroException) kod catch DBZex As DevideByZeroException Hantera ”felet” catch FNFex As FileNotFoundException Hantera ”felet” catch sqlex As SQLException Hantera ”felet” catch ex As Exception Hantera ”felet” finally Avsluta end try Fortsätt med koden. Om det går dåligt, kasta en egen Exception någonstans i din kod. Flera ”nivåer” med Exceptions och hantering av dessa kan radas upp. Egna kan också skapas och hanteras. Ordningen av catch viktig varför jag reserverar mig mot riktigheten i exemplet Kan liknas med Else i en If-sats Körs alltid

27 Felhantering Alltid när du kontaktar system utanför. Några Exceptions System.AppDomainUnloadedException System.ArgumentException System.ArithmeticException System.ArrayTypeMismatchException System.BadImageFormatException System.CannotUnloadAppDomainException System.ComponentModel.Design.Serialization.CodeDomSerializerException System.ComponentModel.LicenseException System.ComponentModel.WarningException System.Configuration.ConfigurationException System.Configuration.Install.InstallException System.ContextMarshalException System.Data.DataException System.Data.DBConcurrencyException System.Data.SqlClient.SqlException System.Data.SqlTypes.SqlTypeException System.Drawing.Printing.InvalidPrinterException System.EnterpriseServices.RegistrationException System.EnterpriseServices.ServicedComponentException System.ExecutionEngineException System.FormatException System.IndexOutOfRangeException System.InvalidCastException System.InvalidOperationException System.InvalidProgramException System.IO.InternalBufferOverflowException System.IO.IOException System.Management.ManagementException System.MemberAccessException System.MulticastNotSupportedException System.NotImplementedException System.NotSupportedException System.NullReferenceException System.OutOfMemoryException System.RankException System.Reflection.AmbiguousMatchException System.Reflection.ReflectionTypeLoadException System.Resources.MissingManifestResourceException

28 Felhantering Alltid när du kontaktar system utanför. Exceptions System.Runtime.InteropServices.ExternalException System.Runtime.InteropServices.InvalidComObjectException System.Runtime.InteropServices.InvalidOleVariantTypeException System.Runtime.InteropServices.MarshalDirectiveException System.Runtime.InteropServices.SafeArrayRankMismatchException System.Runtime.InteropServices.SafeArrayTypeMismatchException System.Runtime.Remoting.RemotingException System.Runtime.Remoting.ServerException System.Runtime.Serialization.SerializationException System.Security.Cryptography.CryptographicException System.Security.Policy.PolicyException System.Security.SecurityException System.Security.VerificationException System.Security.XmlSyntaxException System.ServiceProcess.TimeoutException System.StackOverflowException System.Threading.SynchronizationLockException System.Threading.ThreadAbortException System.Threading.ThreadInterruptedException System.Threading.ThreadStateException System.TypeInitializationException System.TypeLoadException System.TypeUnloadedException System.UnauthorizedAccessException System.Web.Services.Protocols.SoapException System.Xml.Schema.XmlSchemaException System.Xml.XmlException System.Xml.XPath.XPathException System.Xml.Xsl.XsltException

29 SystemException (Det finns mer…) Public Properties HelpLink (inherited from Exception) Gets or sets a link to the help file associated with this exception. InnerException (inherited from Exception) Gets the Exception instance that caused the current exception. Message (inherited from Exception) Gets a message that describes the current exception. Source (inherited from Exception) Gets or sets the name of the application or the object that causes the error. StackTrace (inherited from Exception) Gets a string representation of the frames on the call stack at the time the current exception was thrown. TargetSite (inherited from Exception) Gets the method that throws the current exception. Public Methods ToString (inherited from Exception) Overridden. Creates and returns a string representation of the current exception. Equals (inherited from Object) Overloaded. Determines whether two Object instances are equal. GetBaseException (inherited from Exception) When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. Kan skrivas ut under felsökning Felmeddelanden från SQL är ”bra”

30 <% Dim myConnection As SqlConnection Dim myCommand As SqlCommand ’Dim myParam As SqlParameter Dim myTrans As SqlTransaction myConnection = New SqlConnection( "server=localhost;uid=sa;pwd=secret;database=myData" ) ’Nytt kommando myConnection.Open() myTrans= myConnection.BeginTransaction() myCommand.Transaction =myTrans try myCommand.ExecuteNonQuery() ’Nytt kommando myCommand.ExecuteNonQuery() MyTrans.Commit catch ex as SQLException myTrans.Rollback() finally myConnection.Close() end try %> Transaktioner Du vet att alla SQL-frågorna körts. Det gamla vanliga Startpunkt. Samtliga kommandon måste genomföras, annars ska inget genomföras Allt gick tydligen bra, gör ”commit” Det gick dåligt, ångra allt gör ”rollback” Stäng efter dig

31 Triggers (i databasen) Varje AFTER Trigger kan bara finnas mot en Tabell Databasen uppdateras först när Triggern är avslutad (Rollback möjligt). Man kan ha flera Triggers på samma kommando, första och sista kan bestämmas men övriga vet man inget om. [AFTER är default för Triggers så det kan uteslutas] Databasen uppdateras när/om din kod i Triggern gör det. Endast en INSTEAD OF Trigger för varje kommando och Tabell/Vy Att ändra data i en vy är normalt begränsad, m.h.a INSTEAD OF kan man oftast komma förbi det. INSTEAD OF CREATE TRIGGER namn ON Tabell/Vy INSTEAD OF {INSERT | UPDATE | DELETE} AS SQL-kod GO AFTER CREATE TRIGGER namn ON Tabell (AFTER) {INSERT | UPDATE | DELETE} AS SQL-kod GO

32 Egna funktioner (i databasen) User defined functions input-parametrar men endast 1 resultat (ett värde eller tabell) CREATE FUNCTION namn datatyp [= default], ) TABLE ( column_definition |table_constraint) WITH {ENCRYPTION, SCHEMABINDING} AS BEGIN SQL-KOD RETURN END Ex. money = 0.0

33 Stored ProceduresWhen you create an application with Microsoft® SQL Server™ 2000, the Transact-SQL programminglanguage is the primary programming interface between your applications and the SQL Serverdatabase. When you use Transact-SQL programs, two methods are available for storing and executingthe programs. You can store the programs locally and create applications that send the commands toSQL Server and process the results, or you can store the programs as stored procedures in SQL Server and create applications that execute the stored procedures and process the results. stored proceduresStored procedures in SQL Server are similar to procedures in other programming languages in that theycan: Accept input parameters and return multiple values in the form of output parameters to the calling procedure or batch. Contain programming statements that perform operations in the database, including calling other procedures. Return a status value to a calling procedure or batch to indicate success or failure (and the reason for failure). You can use the Transact-SQL EXECUTE statement to run a stored procedure. Stored procedures aredifferent from functions in that they do not return values in place of their names and they cannot be used directly in an expression. functionsThe benefits of using stored procedures in SQL Server rather than Transact-SQL programs storedlocally on client computers are: They allow modular programming. You can create the procedure once, store it in the database, and call it any number of times in your program. Stored procedures can be created by a person who specializes in databaseprogramming, and they can be modified independently of the program source code. They allow faster execution. If the operation requires a large amount of Transact-SQL code or is performed repetitively, stored procedures can be faster than batches of Transact-SQL code. They are parsed andoptimized when they are created, and an in-memory version of the procedure can be used afterthe procedure is executed the first time. Transact-SQL statements repeatedly sent from theclient each time they run are compiled and optimized every time they are executed by SQLServer. They can reduce network traffic. An operation requiring hundreds of lines of Transact-SQL code can be performed through a single statement that executes the code in a procedure, rather than by sending hundreds of linesof code over the network. They can be used as a security mechanism. Users can be granted permission to execute a stored procedure even if they do not have permission to execute the procedure's statements directly. A SQL Server stored procedure is created with the Transact-SQL CREATE PROCEDURE statementand can be modified with the ALTER PROCEDURE statement. The stored procedure definitioncontains two primary components: the specification of the procedure name and its parameters, and thebody of the procedure, which contains Transact-SQL statements that perform the procedure'soperations.See AlsoCatalog Stored ProceduresSystem Stored Procedures Från Help i SQL-admin


Ladda ner ppt "Databasanslutning TDS- Tabular Data Stream (SQL) OLE DB- Data som kan representeras som rad och kolumn ODBC- Open Data Base Connectivity (Data Source Name."

Liknande presentationer


Google-annonser