How to Connect Visual Basic to SQL

Save

As a programmer you will run into the need to connect to multiple data sources such as SQL databases. Once you make the connection to a SQL server database, you can update or retrieve data from the database tables. In Visual Basic (VB) you can use the ActiveX Data Objects (ADO) to connect to a SQL server. Don't spend time exporting data from SQL to files for your VB application; instead use ADO and retrieve data directly from SQL.

  • Launch Microsoft Visual Basic Express and click "New Project..." on the left pane of your screen then select "Console Application." Click "OK" to create a new console project. Click the "Project" menu and select "<projectname> Properties".

  • Click "References" and click "Add." Click the "COM" tab and click ""Microsoft ActiveX Data Objects <version number> Library"." Click "OK" to add the reference.

  • Import the ADODB namespace by typing the following line of code in the first line of your module:

    Imports ADODB

  • Type the following VB code below "Sub Main()" to create a new variable:

    Dim ADOconnection As New ADODB.Connection

  • Copy and paste the following code to connect to a database in SQL server:

    ADOconnection.ConnectionString = "Provider=SQLNCLI10;" _

                & "Server=SERVER NAME;" _

    & "Database=DATABASE NAME;" _

    & "Integrated Security=SSPI;" _

    & "DataTypeCompatibility=80;" _

    & "MARS Connection=False;"

    ADOconnection.Open()

  • Edit "SERVER NAME" and type the name of your SQL server. Edit "DATABASE NAME" and type the name of the database you want to connect to.

  • Type the following to close your connection when you're done with the connection:

    ADOconnection.Close()

        ADOconnection = Nothing

References

  • Photo Credit Hemera Technologies/AbleStock.com/Getty Images
Promoted By Zergnet

Comments

You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!