Connecting and using SQL in VB.NET
SQL In VB.NET
'Declare outside of class
Imports System.Data.SqlClient
'Declare inside of class >
Dim SQLStr As String
Private ConnString As String
'Connstring = Server Name, Database Name, Windows Authentication
connstring = "Data Source=myserver;Initial Catalog=databasename;Integrated Security=True"
'SQL Staments
'SQL query = myQuery = "SQL Statment"
SQLStr = "SELECT * FROM tblQuestion"
SQLStr = "INSERT into tblQuestion(Name, Question) VALUES('Fred', 'How to use SQL?')"
SQLStr = "UPDATE tblQuestion SET Answer = 'Like this' Where Question = 'How to use SQL?'"
SQLStr = "DELETE FROM tblQuestion WHERE Question='How to use SQL?'"
'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
SQLCmd.ExecuteNonQuery() 'Executes SQL Commands Non-Querys only
SQLConn.Close() 'Close the connection
'Read from SQL
Dim SQLConn As New SqlConnection() 'The SQL Connection
Dim SQLCmd As New SqlCommand() 'The SQL Command
Dim SQLdr As SqlDataReader 'The Local Data Store
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 'Gets Data
While dr.Read() 'While Data is Present
MsgBox(dr("Column Name")) 'Show data in a Message Box
End While
Loop While SQLdr.NextResult() 'Move to the Next Record
SQLdr.Close 'Close the SQLDataReader
SQLConn.Close() 'Close the connection
majestic0110 187 Nearly a Posting Virtuoso
chan_lemo 0 Newbie Poster
ERICKFB5 0 Newbie Poster
alex.ubeda 0 Newbie Poster
css_maya 0 Newbie Poster
tendaimare 0 Junior Poster in Training
Netcode 33 Veteran Poster
inthewind
aniketcool 0 Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.