connectionstring in visual studio 2010 - vb.net

I am kind of new to programming, i am doing a vb.net database project in which i am using access database as my backend database. I am using visual studio 2010.
I have used a folder browser dialog to get the directory where my access .accdb file is. I have used a string to get the the strings together to form a connectionstring. My problem is how can i make the program to wait for me to select a location to complete the connectionstring? how can i prevent the program from looking up the connectionstring in "my settings" tab in my project page....
Also using add datasource wizard,when deployed gives error that db file is not found in the displayed location, and if i check that location i see two files and the db is present in one file but the displayed location is other file.
Private Sub SettingToolStripMenuItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SettingToolStripMenuItem.Click
FolderBrowserDialog1.ShowDialog()
Connectstring = FolderBrowserDialog1.SelectedPath()
connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & Connectstring & "\QuestionPool.accdb;"
connection = New OleDbConnection(connectionstring) 'is not needed. garbage code.
writer = New StreamWriter("Connectionstring.connection")
writer.WriteLine(connectionstring)
writer.Close()
End Sub
also I can't get the
connection = new oledbconnection(connectionstring)
to work.
I have to include home. connectionstring in the dataset.designer.vb to get the connection work.
Also how do I add the connection string variable to my.settings tab?

Related

Change sql server from visual basic form

I want to let the users change the sql server connetion manually from a settings form because the application will be used in many company
i tried this:
i create a string in settings "sqlservername"
then in the loading form i put a textbox "txt_sqlservername" and savebutton
the button event
My.Settings.sqlservername = Me.txt_sqlservername.Text
My.Settings.Save()
MsgBox("Server Name Was Updated", MsgBoxStyle.Information, "Videos Database - New Server Name")
Me.Close()
and this is my connection string
Public SQLCon As New SqlConnection With {.ConnectionString = "Server=My.Settings.sqlservername;Database=Videos;User=sa;Pwd=123456;"}
when i open my main form nothing shown
any help?
You can give a form that asks for user input for the connection string and then save the connection string in the application settings.
You can use this connection string from the settings every time you define a connection in the application.
The string formatting is wrong where the connection is defined.Make correction like shown below:
Public SQLCon As New SqlConnection With {.ConnectionString = "Server=" & My.Settings.sqlservername & ";Database=Videos;User=sa;Pwd=123456;"}

Creating Connections to ODBC Data Sources using codes in vb.net

I am trying to connect using vb.net (Visual studio 2013) to an MS Access Database 2007(.accdb) using codes. But something is wrong in my code and i can't figure it out.
the Database name is "localDatabase.accdb"
I didn't put any password on my database
I'm using a 64bit
Thanks in advance!
Here is my code:
Module Module1
Dim conn As New System.Data.Odbc.OdbcConnection
Public Sub ConnectToOdbc()
conn.ConnectionString = Provider=Microsoft.ACE.OLEDB.12.0;Data Source="C:\Users\MyPc\Documents\Visual Studio 2013\Projects\database\localDatabase.accdb"
Try
conn.Open()
Catch ex As Exception
MessageBox.Show("Failed to connect to data source")
Finally
conn.Close()
End Try
End Sub
End Module
this is just a hypothesis..
I am using ACE 12.0 now on my app, and it works fine. the different thing is the code try to use this..
Imports System.Data.OleDb
'instead of obdc
con = New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & Path.Combine(Application.StartupPath, "YourDatabase.accdb")
'put your .accdb in your app folder
maybe the error is it can't find your .accdb file.
Change this line:
conn.ConnectionString = Provider=Microsoft.ACE.OLEDB.12.0;Data Source="C:\Users\MyPc\Documents\Visual Studio 2013\Projects\database\localDatabase.accdb"
to this:
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\MyPc\Documents\Visual Studio 2013\Projects\database\localDatabase.accdb"
ConnectionString as the name tell is a string, so you need to wrap it with double-quotes to be recognized as string by VB compiler.
UPDATE :
Also you need to change the connection object from Odbc to OleDb:
Dim conn As New System.Data.OleDb.OleDbConnection

Database will read but will not write

I have a problem where I am unable to make a booking to a Sql server .mdf database, but I am able to read to it.
No error messages occur and I have tried everything I can think of. Any help will be highly appreciated and thanks in advance!
Here is the code used for the insert into command:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim SQLCode As New SQLCode
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim lrd As SqlDataReader
Dim inscmd As New SqlCommand
cmd.Parameters.AddWithValue("#StaffInitials", lblStaffInitials.Text.Trim())
lblStaffInitials.Text = lblStaffInitials.Text
cmd.Parameters.AddWithValue("#Week", lblWeek.Text.Trim)
lblWeek.Text = lblWeek.Text
cmd.Parameters.AddWithValue("#Period", (lblPeriod.Text.Trim))
lblPeriod.Text = lblPeriod.Text
cmd.Parameters.AddWithValue("#Day", lblDay.Text.Trim)
lblDay.Text = lblDay.Text
cmd.Parameters.AddWithValue("#Subject", lblSubject.Text.Trim)
lblSubject.Text = lblSubject.Text
cmd.Parameters.AddWithValue("#YearGroup", lblYear.Text.Trim)
lblYear.Text = lblYear.Text
cmd.Parameters.AddWithValue("#NumberOfPupils", (lblNoOfPupils.Text.Trim))
lblNoOfPupils.Text = lblNoOfPupils.Text
cmd.Parameters.AddWithValue("#ControlledAssesment", lblControlledAssesment.Text.Trim)
lblControlledAssesment.Text = lblControlledAssesment.Text
cmd.Parameters.AddWithValue("#Room", lblRoom.Text.Trim)
lblRoom.Text = lblRoom.Text
cmd.Parameters.AddWithValue("#Session", txtSession.Text.Trim)
txtSession.Text = txtSession.Text
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("RoomBookingSystem.My.MySettings.Database1ConnectionString1").ConnectionString
Try
Using cn As New SqlConnection(con.ConnectionString)
con.Open()
inscmd.CommandText = "INSERT INTO Booking (Week, Day, Period, Subject, YearGroup, StaffInitials,NumberOfPupils,Session,Room,ControlledAssesment) VALUES (#Week,#Day,#Period,#Subject,#YearGroup,#StaffInitials, #NumberOfPupils,#Session,#Room,#ControlledAssesment)"
inscmd.Connection = con
inscmd.ExecuteNonQuery()
inscmd.Parameters.Clear()
End Using
Finally
con.Close()
End Try
MsgBox("Your Booking Has Been Made Successfully")
Clicky = False
MainViewForm.btnBackToBooking.Visible = False
FormView.Show()
Me.Hide()
End Sub
As far as I can tell the problem lies within the databases location.
When the program is debugged a copy of your database is placed within the bin/debug folder, if you look in here you will see the copy and your code will right to this database and Not The original Database (if you click show all files then go to the bin/debug file and then open with database explorer you can see the data imputed on the last debug/running)
To fix this you need to do the following:
Your connection string
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("RoomBookingSystem.My.MySettings.Database1ConnectionString1").ConnectionString
Will connect to the database within the bin folder mentioned previously.
You need to go into your app.config file find the specific location for your database and use this for you connection string, this will allow you to insert/update data from the non copy of the database.
You have two different Sql Commands when only one SqlCommand is needed. Add the parameters to inscmd rather than cmd.
So simply remove this line :
Dim cmd As New SqlCommand
and do this for the rest :
inscmd.Parameters.AddWithValue("#StaffInitials", lblStaffInitials.Text.Trim())
.....
.....
Another thing to note, you don't need this :
Using cn As New SqlConnection(con.ConnectionString)
Change your code like this :
Try
con.Open()
inscmd.CommandText = "INSERT INTO Booking (Week, Day, Period, Subject, YearGroup, StaffInitials,NumberOfPupils,Session,Room,ControlledAssesment) VALUES (#Week,#Day,#Period,#Subject,#YearGroup,#StaffInitials, #NumberOfPupils,#Session,#Room,#ControlledAssesment)"
inscmd.Connection = con
inscmd.ExecuteNonQuery()
inscmd.Parameters.Clear()
Catch ex As Exception
// use message box to read the error (if there is any). or simply read the
// ex.Message in debuggin mode.
Finally
con.Close()
End Try
and by the way I don't see where you are setting this property con.ConnectionString. where is your connection string?

Vb.net 2010 Connection to SQL Server 2008

I am trying to connection to MS SQL SERVER 2008 database (students), i want to make sure:
1) If connection string that i made is OK
Dim connectionString As New SqlConnection("server=X86ONX64; database=students; Integrated Security=True")
2) How can i check if dataset is producing any results?
Code:
Public Class Form1
'Connection String + DataAdaptor + DataSet
'Declared Outside Any Subroutines/Functions
Dim connectionString As New SqlConnection("server=X86ONX64; database=students; Integrated Security=True")
Dim dataAdaptor As New SqlDataAdapter()
Dim objdataSet As New DataSet()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dataAdaptor.SelectCommand = New SqlCommand()
dataAdaptor.SelectCommand.Connection = connectionString
dataAdaptor.SelectCommand.CommandText = "select * from basic_info;"
dataAdaptor.SelectCommand.CommandType = CommandType.Text
connectionString.Open()
dataAdaptor.Fill(objdataSet, "StudentInfo")
connectionString.Close()
grd.AutoGenerateColumns = True
grd.DataSource = objdataSet
grd.DataMember = "basic_info"
dataAdaptor = Nothing
connectionString = Nothing
End Sub
About your first question, If connection string that i made is OK
If you did not get any exceptions, you've successfully made the connection to your database.
About your second question.
There are two things you can do.
Debug the wrong way. (It works though)
MsgBox(objdataSet.Tables[0].Rows.Count);
Learn and debug the correct way.
Read these articles
Debugging Basics
Visual Studio Debugging
Debugging Basics: Breakpoints
Anyway, learn how to use the debugger properly, put a break point, analyse the objdataSet object in a watch window and see if any results are present.
1) If connection string that i made is OK
Easy way to verify connection strings is to connect using the "Server Explorer" in Visual Studio. Once you get a good connection, right-click on the connection and just grab the "Connection String" property.
2) How can i check if dataset is producing any results?
MsgBox(objdataSet.GetXML)
GetXML will return ALL the data in the dataset in XML format.
Also, don't globally declare variables if you don't need to.
Declare them closer, or not at all, like so...
Dim objdataSet As New Data.DataSet()
Using connectionString As New Data.SqlClient.SqlConnection("server=X86ONX64; database=students; Integrated Security=True")
With New Data.SqlClient.SqlDataAdapter()
.SelectCommand = connectionString.CreateCommand
.SelectCommand.CommandText = "select * from basic_info;"
.SelectCommand.CommandType = Data.CommandType.Text
.Fill(objdataSet, "StudentInfo")
End With
MsgBox(objdataSet.GetXML)
End Using
'Now put it in your dataset...'
Hope this helps.

how to keep a odbc connection open in vb.net

I'm trying to connect to a database and keep the connection open for any amount of user activity/queries within the database. Currently I have a connection that opens and closes for any query (save, update, etc...) which requires the logon process to the back-end every time the user saves etc... Is there a way to simply connect and leave the connection open so there won't be a lag time when running the query due to the logon process? This is what I'm using:
Private sConStrFormat As String = "Provider=TDOLEDB;Data Source=TDDEV;Persist Security Info=True;User ID={0};Password={1};Default Database=bcpm_ddbo;Session Mode=ANSI;"
Private Sub cmdsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdsave.Click
Dim sSQL As String
Dim sConStr As String
Dim user As String
Dim pass As String
user = txtuser.Text
pass = txtpass.Text
Dim UserName As String = user
Dim Password As String = pass
sConStr = String.Format(sConStrFormat, UserName, Password)
Using Con As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection(sConStr)
Con.Open()
sSQL = "INSERT INTO LTC_FBS (CLM_NUM) VALUES ('" & Me.txtClaim.Text & "')"
Dim cmdins As New System.Data.OleDb.OleDbCommand(sSQL, Con)
cmdins.ExecuteNonQuery()
Con.Close()
End Using
End Sub
.Net automatically maintains a connection pool for you. According to MSDN, when you call Close() on the Connection the framework
releases the connection to the
connection pool, or closes the
connection if connection pooling is
disabled
In vb.net 4.5 do the following:
At the top straight after the class definer put in this line:
Public Shared conn As OdbcConnection
Then, in the subs where you want to use the connection use this line:
If conn Is Nothing Then conn = New OdbcConnection(<your_connection_string>): conn.Open()
Then the New OdbcCommand will use the existing connection without opening a new one. Don't close the connection in your script until you are quite certain you're finished with it (_Shutdown is a good spot and you're good to go.
This also solves problems with MySQL when constantly opening new connections causes the max connections error.
Instead of defining 'con' in the using statement, define it up above as a static variable. When the function is called, you can see if 'Con' has been assined or not. If not, you build your connection string and set Con = New OleDBConnection, and open it. Since it's a static variable, it will retain its value at the next call. Check that it's not nothing, and then use it right away. Make sure you don't call close in the routine or the connection will not remain open.