Wednesday, August 10, 2011

SQL et Vb.Net

Voici un exemple de connexion à un serveur SQL avec une requête simple (SELECT)
puis un UPDATE sur les résultats trouvés par la première requête


Il est possible de faire comme dans le POST précèdent ACCESS et VB.NET une classe connexion afin de mieux gérer votre code et répéter le moins possible votre code.


Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient

Private Const BDSQLCONNEXIONSTRING As String = "Data Source=SERVEUR;Initial Catalog=NOM_DE_LA_TABLE;Integrated Security=True"

Private Sub testSQL()

Dim SQLStr As String
Dim ConnString As String
Dim SQLdr As SqlDataReader
'Connstring = Server Name, Database Name, Windows Authentication

ConnString = BDSQLCONNEXIONSTRING
'SQL Staments
SQLStr = "SELECT * FROM TABLE"


'Write to SQL
Dim SQLConn As New SqlConnection() 'The SQL Connection
Dim SQLCmd As New SqlCommand() 'The SQL Command

SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open() 'Open the connection

SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
SQLCmd.CommandText = SQLStr 'Sets the SQL String

SQLdr = SQLCmd.ExecuteReader
While SQLdr.Read() 'While Data is Present

Dim query As String = "VOTRE REQUETE"
ConnexionSQL(query)

End While


SQLConn.Close() 'Close the connection

End Sub

Private Sub ConnexionSQL(ByVal q As String)
Dim ConnString As String
ConnString = BDSQLCONNEXIONSTRING

Dim SQLCmd2 As New SqlCommand() 'The SQL Command
Dim SQLConn2 As New SqlConnection()
SQLConn2.ConnectionString = ConnString 'Set the Connection String
SQLConn2.Open() 'Open the connection
SQLCmd2.Connection = SQLConn2
SQLCmd2.CommandText = q
SQLCmd2.ExecuteNonQuery()
SQLConn2.Close()

End Sub

No comments:

Post a Comment