Sunday, March 27, 2011

VISUAL BASIC 2010 EXPRESS & SQL SERVER 2008 EXPRESS

Two great tools that go great together 

VB.Net and SQL Server are powerful, industry-standard development tools from Microsoft.  It’s sometimes surprising to realize that anyone can download and use these programs for free.

Getting them installed and working together took longer than I expected.  Google searches showed that many people were even questioning whether a VB Express program could could access a SQL Server Express database.  It can, but there’s a trick to it.

So if you’re trying to get started with your first VB+SQL program, here’s a small app to start you off.  I hope it saves you a couple hours!
______________________________________________

First, download and install Visual Basic 2010 Express and Sql Server 2008 Express from www.microsoft.com/express. 

SQL Server

Next, start Sql Server Management Studio, and log in.
 (Start à All Programs à Microsoft SQL Server 2008 à SQL Server 2008)

Create a new database by right-clicking Databases and selecting New Database

Name the new database MyTestDB and click OK.

Expand the Databases folder to find your new database:

Click New Query and run this script to create an empty table named tblTest:

CREATE TABLE [MyTestDB].[dbo].[tblTest] (
   [tstNum_PK] [int] IDENTITY(1,1) NOT NULL ,
   [tstData] [varchar] (100) NOT NULL
) ON [PRIMARY]

Visual Basic 
Now start Visual Basic and create a new Windows Form Application named DatabaseTest. 
(Start à All Programs à Microsoft Visual Studio 2010 Express à Visual Basic 2010)

On your VB Form, add two TextBoxes and two Buttons.  For simplicity, we’ll leave the their properties at their default settings and change them in the code.


à Here’s the trick: with Visual Basic 2010 Express, you have to connect directly to the database file.  You may be used to connecting to remote database servers – you can’t do that here.  When you created MyTestDB above, SQL Server created a file on your PC named MyTestDB.mdf.  Find it, and if the full path name is different from:

C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\MyTestDB.mdf

Then you’ll need to change two lines in this sample code to match your location.

Add the code below to your program.  Now you’re ready to run.

Start the program and type something into the first text box.  Then click Add to DB. 
Unless you see an error message, a new record was just written to your database.

To read and display all the records in this table, click Show DB.
The ‘1’ at the beginning is the Primary Key for your record – a field you generally want to include, but would rarely display.

That’s it.  If you got all the way through, you now have a working (though bare-bones) program to begin developing your own applications.  Good luck!

 
Imports System.Data.SqlClient 
Public Class Form1

   'at program startup, set the control properties
   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      Button1.Text = "Add to DB"
      Button2.Text = "Show DB"
      TextBox2.Multiline = True
   End Sub 

   'write a record to the database table
   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      Dim sqCon As New SqlClient.SqlConnection("Server=.\SQLExpress;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\MyTestDB.mdf;Database=MyTestDB; Trusted_Connection=Yes;")
      Dim sqCmd As New SqlClient.SqlCommand

      sqCmd.Connection = sqCon            'create the DB connection
      sqCmd.CommandText = "INSERT INTO [MyTestDB].[dbo].[tblTest] VALUES ('" & TextBox1.Text & "')"
      sqCon.Open()                        'open the connection
      sqCmd.ExecuteNonQuery()             'execute the SQL command
      sqCon.Close()                       'close the connection
   End Sub 

   'read and display all records from the database table
   Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
      Dim sqCon As New SqlClient.SqlConnection("Server=.\SQLExpress;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\MyTestDB.mdf;Database=MyTestDB; Trusted_Connection=Yes;")
      Dim sqCmd As New SqlClient.SqlCommand
      Dim sdrRow As SqlClient.SqlDataReader

      'define the DB connection and search string
      sqCmd.Connection = sqCon
      sqCmd.CommandText = "SELECT * FROM tblTest"

      'open the DB connection
      sqCon.Open()                        'open the DB connection
      sdrRow = sqCmd.ExecuteReader()      'read the entire table

      'extract and display each field
      TextBox2.Text = ""                  'clear the text box
      Do While sdrRow.Read()
         TextBox2.Text = TextBox2.Text & sdrRow.GetValue(0) & vbTab     'get the primary key
         TextBox2.Text = TextBox2.Text & sdrRow.GetValue(1) & vbCrLf    'get the string
      Loop

      'close up and return
      sdrRow.Close()
      sqCon.Close()

   End Sub
End Class

7 comments:

  1. Hey, this has helped my begin to understand the concepts behind creating a DB for VB.

    Using your code above im getting an error when it tries to open a connection to the DB. I get the error below while debugging:

    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

    ReplyDelete
  2. Hi - the SQL service is probably not running; I can reproduce this error by stopping SQL. To run the service:
    - Bring up your Control Panel (Start --> Control Panel)
    - Click Administrative Tools
    - Click Services
    - Doubleclick SQL Server
    - Click Start, under Server Status (if you can click it, then the service wasn't running)

    BTW, these steps are for XP and might be different for other versions of Windows. Good luck!

    ReplyDelete
  3. Hi!, i have some troubles with my code
    When i start to run the program it send me a error message
    On the sqCon.Open()
    It says:
    it cant be open the data base 'InventarioZisro' in version 661. This server is compatible with version 655 an earlier.

    What means that?

    ReplyDelete
  4. Were you restoring a database, or reloading the software? Here's a good thread that discusses the problem, and provides some answers:

    http://social.msdn.microsoft.com/Forums/en/sqldatabaseengine/thread/f8f8db38-3c20-45e4-ae8b-4cc097eb7f0d

    ReplyDelete
  5. Thank you for your very clear instructions above. There were indications of what you said on other q&a but yours is the first that I found that gave the code in full and explained exactly why I couldn't get a connection using the wizard. Keep up the good work :) And yes I agree with your first paragraph - I'm amazed too and now I can do some fun stuff at home for charity purposes with good quality products(very rusty on my VB skills) - Wow.

    ReplyDelete
  6. Thank you so much MichiKami, just bump to your page while searching the net.. It will really save me a lot of hours.. :) More power and God bless..

    ReplyDelete
  7. Thank you very mutch for your explication help me a lot!

    ReplyDelete