DaniWeb IT Discussion Community

Code Snippets (http://www.daniweb.com/code/)
-   vbnet (http://www.daniweb.com/code/vbnet.html)
-   -   SQL In VB.NET (http://www.daniweb.com/code/snippet696.html)

ptaylor965 vbnet syntax
Apr 29th, 2007
Connecting and using SQL in VB.NET

  1. 'Declare outside of class
  2. Imports System.Data.SqlClient
  3.  
  4.  
  5. 'Declare inside of class >
  6. Dim SQLStr As String
  7. Private ConnString As String
  8.  
  9. 'Connstring = Server Name, Database Name, Windows Authentication
  10. connstring = "Data Source=myserver;Initial Catalog=databasename;Integrated Security=True"
  11.  
  12. 'SQL Staments
  13.  
  14. 'SQL query = myQuery = "SQL Statment"
  15.  
  16. SQLStr = "SELECT * FROM tblQuestion"
  17.  
  18. SQLStr = "INSERT into tblQuestion(Name, Question) VALUES('Fred', 'How to use SQL?')"
  19.  
  20. SQLStr = "UPDATE tblQuestion SET Answer = 'Like this' Where Question = 'How to use SQL?'"
  21.  
  22. SQLStr = "DELETE FROM tblQuestion WHERE Question='How to use SQL?'"
  23.  
  24. 'Write to SQL
  25.  
  26. Dim SQLConn As New SqlConnection() 'The SQL Connection
  27. Dim SQLCmd As New SqlCommand() 'The SQL Command
  28.  
  29. SQLConn.ConnectionString = ConnString 'Set the Connection String
  30. SQLConn.Open 'Open the connection
  31.  
  32. SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
  33. SQLCmd.CommandText = SQLStr 'Sets the SQL String
  34. SQLCmd.ExecuteNonQuery() 'Executes SQL Commands Non-Querys only
  35.  
  36. SQLConn.Close() 'Close the connection
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46. 'Read from SQL
  47.  
  48. Dim SQLConn As New SqlConnection() 'The SQL Connection
  49. Dim SQLCmd As New SqlCommand() 'The SQL Command
  50. Dim SQLdr As SqlDataReader 'The Local Data Store
  51.  
  52. SQLConn.ConnectionString = ConnString 'Set the Connection String
  53. SQLConn.Open 'Open the connection
  54.  
  55. SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
  56. SQLCmd.CommandText = SQLStr 'Sets the SQL String
  57. SQLdr = SQLCmd.ExecuteReader 'Gets Data
  58.  
  59. While dr.Read() 'While Data is Present
  60. MsgBox(dr("Column Name")) 'Show data in a Message Box
  61. End While
  62.  
  63. Loop While SQLdr.NextResult() 'Move to the Next Record
  64. SQLdr.Close 'Close the SQLDataReader
  65.  
  66. SQLConn.Close() 'Close the connection