473,466 Members | 1,455 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Estabhlishing a Connection to my Database

33 New Member
Expand|Select|Wrap|Line Numbers
  1. Imports System.Data.OleDb
  2. Public Class Form1
  3.     Dim conn As OleDbConnection
  4.     Dim constring As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Denden\Desktop\DB.mdb"  'i remove my db on desktop
  5.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  6.  
  7.         conn = New OleDbConnection(constring)
  8.         Try
  9.             If conn.State <> ConnectionState.Open Then
  10.                 conn.Open()
  11.                 MsgBox("connected")
  12.             Else
  13.                 MsgBox("failed")
  14.             End If
  15.         Catch ex As Exception
  16.             ex.Message.ToString()
  17.         End Try
  18.  
  19.         conn.Close()
  20.  
  21.     End Sub
  22. End Class
  23.  
i intentionally remove the database on my desktop just to try if my else code will execute but to my surprise the else statement didnt prompt.. Why that happens?
Sep 21 '14 #1
10 1631
Rabbit
12,516 Recognized Expert Moderator MVP
It's because you're checking if the state is not open. It's never going to be open before the check so it will never run the else.
Sep 21 '14 #2
Denden
33 New Member
i opened the connection before message will appear.
Sep 22 '14 #3
Rabbit
12,516 Recognized Expert Moderator MVP
Yes, you open it before the message appears. The problem is you open it after you check if it's open. Therefore, it is never open before you check.
Sep 22 '14 #4
Denden
33 New Member
@Rabbit
so is this the correct way?
Expand|Select|Wrap|Line Numbers
  1. If conn.State = ConnectionState.Closed Then
  2.             conn.Open()
  3.             MsgBox("Open")
  4.         Else
  5.             MsgBox("Close")
  6.  
  7.         End If
  8.  
  9.  
Oct 12 '14 #5
Rabbit
12,516 Recognized Expert Moderator MVP
No, what I'm saying is you're testing a condition that will only ever go down one path. The if else is pointless. Basically, what you are doing is similar to this:
Expand|Select|Wrap|Line Numbers
  1. x = 0
  2.  
  3. If x = 0 Then
  4.    x = 1
  5.    MsgBox(x)
  6. Else
  7.    MsgBox("else part of code")
  8. End If
The code will never ever ever run the Else portion of the code because x will never not be 0. That's what your code is doing. Your connection will never be open because the only time you try to open the connection is after you do the check.
Oct 12 '14 #6
Denden
33 New Member
got it sir. i must open the connection before using the if statement :) it often see codes goes that way. Thats for enlightening my mind. Just a newbie.

Expand|Select|Wrap|Line Numbers
  1. Dim x As Integer
  2.         x = 1
  3.         If x = 0 Then
  4.             MsgBox(x)
  5.         Else
  6.             MsgBox("else part of code")
  7.         End If
  8.  
Oct 12 '14 #7
Frinavale
9,735 Recognized Expert Moderator Expert
Check out the documentation for the OleDBConnection class. It contains a lot of useful information and code examples.

For example, the suggest utilizing the using statement to help manage resources.

Like this:
Expand|Select|Wrap|Line Numbers
  1.  Using connection As New OleDbConnection(connectionString)
  2.         ' The insertSQL string contains a SQL statement that 
  3.         ' inserts a new row in the source table. 
  4.         Dim command As New OleDbCommand(insertSQL)
  5.  
  6.         ' Set the Connection to the new OleDbConnection.
  7.         command.Connection = connection
  8.  
  9.         ' Open the connection and execute the insert command. 
  10.         Try
  11.             connection.Open()
  12.             command.ExecuteNonQuery()
  13.         Catch ex As Exception
  14.             Console.WriteLine(ex.Message)
  15.         End Try 
  16.         ' The connection is automatically closed when the 
  17.         ' code exits the Using block. 
  18.     End Using 
Notice how they have a Try...Catch block around opening the connection and executing SQL commands with it?

That's because an exception will be thrown if a connection to the database cannot be established or if something else went wrong executing the SQL commands.

The catch section is the section you are interested in...

-Frinny
Oct 16 '14 #8
Denden
33 New Member
@frinavale

i am reading the articles @home&learn website and i found it different from yours, here the way they did on how to update data on database

Expand|Select|Wrap|Line Numbers
  1. Dim cb As New OleDb.OleDbCommandBuilder(da)
  2.         ds.Tables("Denden").Rows(inc).Item(1) = TextBox1.Text
  3.         ds.Tables("Denden").Rows(inc).Item(2) = TextBox2.Text
  4.         da.Update(ds, "Denden")
  5.         MsgBox("Data updated")
  6.  
  7.  
so how it is different from yours? what would be the best option between those.

i also checked the documentation
here what it is looks like
Expand|Select|Wrap|Line Numbers
  1. Public Sub OpenConnection(ByVal connectionString As String)
  2.  
  3.         Using connection As New OleDbConnection(connectionString)
  4.             Try
  5.                 connection.Open()
  6.                 Console.WriteLine("DataSource: {0} Database: {1}", _
  7.                     connection.DataSource, connection.Database)
  8.             Catch ex As Exception
  9.                 Console.WriteLine(ex.Message)
  10.             End Try 
  11.             ' The connection is automatically closed when the 
  12.             ' code exits the Using block. 
  13.         End Using 
  14.     End Sub
  15. ' Define other methods and classes here

i was confused seeing that, would you mind explain this line of code
Expand|Select|Wrap|Line Numbers
  1.  Console.WriteLine("DataSource: {0} Database: {1}", _
  2.                     connection.DataSource, connection.Database)

and lastly can i substitute this line
Expand|Select|Wrap|Line Numbers
  1. Public Sub OpenConnection(ByVal connectionString As String)
to something like this

Expand|Select|Wrap|Line Numbers
  1. Public Sub OpenConnection()
  2. dim connectionString as string
  3.  
many thanks sir.
Oct 18 '14 #9
Frinavale
9,735 Recognized Expert Moderator Expert
Hi Denden,

...how it is different from yours? what would be the best option between those.
It looks like this code is using a DataSet and a DataAdapter to update the database. You don't need to use a DataSet nor do you need to use a DataAdapter to execute an insert/update/delete command; however, using these controls do have their advantages especially if you are planning on updating a whole bunch of records at the same time.
Expand|Select|Wrap|Line Numbers
  1. Dim cb As New OleDb.OleDbCommandBuilder(da)
  2.         ds.Tables("Denden").Rows(inc).Item(1) = TextBox1.Text
  3.         ds.Tables("Denden").Rows(inc).Item(2) = TextBox2.Text
  4.         da.Update(ds, "Denden")
  5.         MsgBox("Data updated")
  6.  
  7.  
The code that I posted simply creates a connection, opens the connection and executes an insert command.
Expand|Select|Wrap|Line Numbers
  1.  Using connection As New OleDbConnection(connectionString)
  2.         ' The insertSQL string contains a SQL statement that 
  3.         ' inserts a new row in the source table. 
  4.         Dim command As New OleDbCommand(insertSQL)
  5.  
  6.         ' Set the Connection to the new OleDbConnection.
  7.         command.Connection = connection
  8.  
  9.         ' Open the connection and execute the insert command. 
  10.         Try
  11.             connection.Open()
  12.             command.ExecuteNonQuery()
  13.         Catch ex As Exception
  14.             Console.WriteLine(ex.Message)
  15.         End Try 
  16.         ' The connection is automatically closed when the 
  17.         ' code exits the Using block. 
  18.     End Using 
  19.  
So, to answer your question, I would recommend using the OleDbDataAdapter solution if you are planning on inserting/updating/deleting a bunch of records at the same time.



... would you mind explain this line of code
Expand|Select|Wrap|Line Numbers
  1.  Console.WriteLine("DataSource: {0} Database: {1}", _
  2.                     connection.DataSource, connection.Database)
This code prints the DataSource property and the Database property of the OleDBConnection object onto the screen.

and lastly can i substitute this line
Expand|Select|Wrap|Line Numbers
  1. Public Sub OpenConnection(ByVal connectionString As String)
to something like this

Expand|Select|Wrap|Line Numbers
  1. Public Sub OpenConnection()
  2. dim connectionString as string
  3.  
Of course you can!
You just need some way to get the connection string...It could even be stored in a .config file.



-Frinny
Oct 20 '14 #10
Denden
33 New Member
wow. thumbs up for the explanation. by the way, im using datareader in reading data, is that the best to use.
Oct 21 '14 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Bina Desai | last post by:
I get the following error: Error Type: Microsoft VBScript runtime (0x800A01A8) Object required: '' /myweb4/authorised_user_page.asp, line 70 and line 70 of my code is: <% rsCheckUser1.Open...
1
by: Barnes | last post by:
I have an asp form that sends data to a redirect page with SQL using JScript. There is a function that I'm using called replace(). The form submits without errors and goes to the redirect page but...
6
by: ABC | last post by:
Follow my project, the connection database will not use Trused Connection from web server to database server. How to set DAAB's connection string with No Credentials Access?
0
by: amber | last post by:
Hello, Not sure what is going wrong here. I just upgraded to .NET 2005 and SQL Server Express 2005 from .NET 2003 and MSDE. I've been working on a huge project for ages, which I 'converted' to...
8
by: Ike | last post by:
Is anyone aware of a means of connection pooling (to MySQL, say) in php? Thanks, Ike
3
by: OutdoorGuy | last post by:
Greetings, I am attempting to use VB.NET 2003 to loop through all of the tables in a SQL Server 2005 database. However, I have yet to figure this out. Does anyone have any suggestions? My...
2
by: bylum | last post by:
help find error that connection database and jsp.. <% String connectionURL = "jdbc:mysql://localhost:3306/webaudio?user=root"; Connection connection = null; Statement statement = null;...
1
by: bylum | last post by:
help find error that connection database and jsp.. <% String connectionURL = "jdbc:mysql://localhost:3306/webaudio?user=root"; Connection connection = null; Statement statement = null;...
4
by: =?Utf-8?B?ZGF2aWQ=?= | last post by:
When I start the Visual Studio .NET 2005 on client machine, I select Tools and database connection (Database: SQL Server, security: windows authentication. Server: Server Machine name (not in the...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.