Refresh SQL Server Credentials - vb.net

How can I refresh my connection strings without reloading/restarting my application? When I put correct credentials in the textbox through my.settings (app.config) it opens when I put incorrect credentials without restarting the app still opens but I should expect “cannot open database “mydb” requested by the login…” How can I do it in vb.net here’s my tested codes.
Try
Using connection as New sqlClient.sqlConnection(constr)
Connection.open()
If connection.state=connectionstate.open then
Msgbox(“Online”)
Else
Msgbox(“Offline”)
End if
End using
Catch sqex as sqlclient.sqlconnection
Msgbox(sqex.message)
End Try
Connection String in Module1
Public constr As String = "Data source='" & My.Settings.myserver & "';
' database='" & My.Settings.mydb & "';
' uid='" & My.Settings.myuid & "';
' password='" & My.Settings.mypwd & "';
' connection timeout=0;
' Max Pool Size=32767; Pooling=True"
Where
Textbox1 = server
Textbox2 = db
Textbox3 = uid
Textbox4 = pwd

Related

VB.NET database is not in MS Access and login error

I use Microsoft Access to store the data. The register form shows msgbox that the data was saved but there isn't any data stored in the table when I check the table on Microsoft Access. Is it supposed to be like that or did I code wrong?
This is my register code
If PasswordTextBox.Text.Length >= 8 Then
Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb")
Dim insert As String = "Insert into Table1 values('" & NameTextBox.Text & "','" & Staff_IDTextBox.Text & "','" & Phone_NoTextBox.Text & "','" & UsernameTextBox.Text & "','" & PasswordTextBox.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
'cmd.ExecuteNonQuery()
MsgBox("Saved")
For Each txt As Control In Me.Controls.OfType(Of TextBox)()
txt.Text = ""
Next
Catch ex As Exception
MsgBox("Error")
End Try
Else
MsgBox("Password must be more than 8 character")
End If
End If
This is my login code
uname = UsernameTextBox.Text
pword = PasswordTextBox.Text
Dim query As String = "Select password From Table1 where name= '" & uname & "';"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Try
pass = cmd.ExecuteScalar().ToString
Catch ex As Exception
MsgBox("Username does not exit")
End Try
If (pword = pass) Then
MsgBox("Login succeed")
Else
MsgBox("Login failed")
UsernameTextBox.Clear()
PasswordTextBox.Clear()
End If
There is an error at this line
pass = cmd.ExecuteScalar().ToString
It says:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Your "cmd.ExecuteNonQuery" is commented out, so the code will not save anything to the database.
You should close your connection after executing the INSERT command.
By default the table will have auto-numbered field as the first item in the table. You will need to remove this field from your table for that specific INSERT command to work.
Or you may need to use a slightly different INSERT command. It is useful to have auto-numbered ID fields in a table.
You probably should catch the exception and display ex.Message in your message box rather then "Error". The ex.Message will be much more helpful to you in debugging your program.
I have made all of these mistakes in my code at one time or other.
Your Login Code;
1)
You should catch the exception message and display in it a message box. This will make debugging faster.
The actual exception in your code will read "{"No value given for one or more required parameters."}
Your query is incorrect.
You should do the open, query, and close of the connection inside the Try-Catch block. Test for a null password afterwards to determine if the username does not exist.
Two separate answers provided, because you have two very separate questions.
Best wishes...

Input username and password for SQL Server from userform VBA Excel

I want to input username and password SQL Server from userform VBA Excel, but I don't understand how to do that. So I create code like this:
Sub OPenCOnn()
Set cnn = New ADODB.Connection
cnn.ConnectionString = "Provider=SQLOLEDB;Data Source=172.20.20.20;Initial Catalog=bank;User ID=" & txtUser.Text & ";Password=" & txtPass.Text & ";"
End Sub
But its didn't work. I receive the below error:
run time error, object required
You need single quotes around the strings like this:
cnn.ConnectionString = "Provider=SQLOLEDB;Data Source=172.20.20.20;Initial Catalog=bank;User ID='" & txtUser.Text & "';Password='" & txtPass.Text & "';"
run time error, object required
You are getting that error because your code cannot find txtUser and txtPass
Ensure the textboxes are there.
Use Option Explicit on the top of your code and then you will notice that it will highlight txtUser and say that Variable not defined. Of Course you will have to also define cnn as Dim cnn As ADODB.Connection

Export from Excel to SQL: Login Failed for User

I'm trying to create a function within Excel that will write data to my remote SQL Server database with a click of a button. However, I keep getting an error telling me that that my login failed for user "UserName" (Error 80040e4d).
At first I thought there must be a problem with my User/Login within the database, so I went to the remote desktop, opened SQL Server Management Studio and checked all my permissions, made sure Windows authentication was selected, checked the password etc... Still didn't work.
My User has been given Read and Write permissions, so I tried to import data into Excel from SQL, which did work. So I'm assuming this must be an issue within my VBA code, more specifically, my connection string.
I would appreciate it if someone could take a look over it, and tell me what I'm doing wrong? Or if someone else has had this issue and knows what's causing it?
Here's the code I have:
Sub Button3_Click()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sArtistId, sForename, sSurname, sNationality, sBirthDate, sDeathDate As String
With Sheets("NewArtist")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=tcp:IPADDRESS,1433\SqlServer2008;" & _
"Initial Catalog=DatabaseName;User ID=UserName;Password=PassWord" & _
"Integrated Security=SSPI;"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
sCustomerId = .Cells(iRowNo, 1)
sFirstName = .Cells(iRowNo, 2)
sLastName = .Cells(iRowNo, 3)
'Generate and execute sql statement to import the excel rows to SQL Server table
conn.Execute "insert into dbo.Components (ArtistId, Forename, Surname, Nationality, BirthDate, DeathDate) values ('" & sArtistId & "', '" & sForename & "', '" & sSurname & "', '" & sNationality & "', '" & sBirthDate & "', '" & DeathDate & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Artists imported."
conn.Close
Set conn = Nothing
End With
End Sub
Thank you very much!
TW
Integrated Security=SSPI
this parameter in your connection string means you are going to pass your windows principal name as authentication, so the sql login and password are being ignored.
you should remove this name/value pair from the connection string, if you want to use a specified username and password.

System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed

I am having a problem with a customer service module which is in a different solution. the problem I think is in my method of calling or getting a connection
here is my class called DBConnForAccess
Imports System.Data.OleDb
Imports System.Data.Odbc
Public Class DBConnForAccess
Dim Conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim Trans As OleDbTransaction
Public Function DBConnect(ByVal filePath As String, pass As String)
Try
' open Database
'Conn = New SqlConnection("Data Source=" + ServerName + "\" + DBName + ";User ID=" + DBUsername + ";Password=" + DBPassword + ";Initial Catalog= '" + TB + "'")
Conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Jet OLEDB:Database Password=" + pass + ";")
' "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;"
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
' create transaction
Trans = Conn.BeginTransaction
Return "Ok"
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Sub ExecuteSQL(ByVal sql As String, ByVal ParamArray Obj() As Object)
' command Object
Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)
'add the parameters to the sql command
Dim I As Integer
For I = 0 To Obj.Length - 1
CMD.Parameters.AddWithValue("#" & I, Obj(I))
Next
'execute the sql
CMD.ExecuteNonQuery()
End Sub
Public Sub commit()
Me.Trans.Commit()
Me.Trans = Me.Conn.BeginTransaction
End Sub
Public Sub rollback()
Me.Trans.Rollback()
Me.Trans = Me.Conn.BeginTransaction
End Sub
Public Sub CloseDB()
Me.Conn.Close()
Me.Conn.Dispose()
Me.Trans.Dispose()
End Sub
Public Function ReadData(ByVal sql As String, ByVal ParamArray Obj() As Object)
' command Object
Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)
'add the parameters to the sql command
Dim I As Integer
For I = 0 To Obj.Length - 1
CMD.Parameters.AddWithValue("#" & I, Obj(I))
Next
Dim R = CMD.ExecuteReader()
'Do While R.Read
'Loop
Return R
End Function
End Class
Here is the Sub I use to fetch Data:
Dim connection As String = txt_util.readFromTextFile("ConnStr_2.txt", 0) + "Billing.mdb"
'connection string is in a text file with text at line 0 as "C:\BILLSERV\"
Private Sub searchAccnt(ByVal SIN As String)
'clear other fields
Clear("Acct")
Try
AccntDetail.DBConnect("ConcessionairesAccnt")
'Dim RS = AccntDetail.ReadData("Select * From AllAccounts Where SIN=#0", txtSIN.Text.Trim)
Dim RS = AccntDetail.ReadData("Select * From viewCSFAccnt Where SIN=#0", SIN)
RS.Read()
If RS.Hasrows = 0 Then
MsgBox("Accounts not found. Check the SIN you Enter.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records not found.")
'txtAppNo.Focus()
Exit Sub
Else
'MsgBox("Accounts correct.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records found.")
txtZoneNo.Text = RS.Item("Zone").ToString
txtSeq.Text = RS.Item("SeqNo").ToString
txtAccntName.Text = RS.Item("AccountName").ToString
txtAccntAddress.Text = RS.Item("HouseNo").ToString + " " + RS.Item("BLDGName").ToString + " " + RS.Item("Street").ToString + _
" " + RS.Item("BRGY").ToString
txtMeterNo.Text = RS.Item("MeterNo").ToString
txtAccntStatus.Text = varA.AccntStatus(RS.Item("Status").ToString)
'Dim con = AccessAccnt.DBConnect(connection, "")
'If con <> "Ok" Then
' MsgBox("Cannot establish a Connection to the server.", MsgBoxStyle.Critical, "Connection Lost...")
'End If
Dim ZoneNo = "Z" + GetChar(txtZoneNo.Text, 1) + GetChar(txtZoneNo.Text, 2) + "B" + GetChar(txtZoneNo.Text, 3) + GetChar(txtZoneNo.Text, 4)
AccessAccnt.DBConnect(connection, "")
Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=#1", txtSeq.Text)
Acc.Read()
txtLastReading.Text = Acc.Item("LastReading").ToString
Acc.close()
AccessAccnt.CloseDB()
End If
RS.Dispose()
AccntDetail.CloseDB()
dbCounter.DBConnect("ConcessionairesAccnt")
Dim result = dbCounter.ReadData("Select Top 1 CSFNo From CSFMaster WHERE (CSFNo LIKE '%" & ctrDate() & "%') order by CSFNo Desc")
result.read()
If result.hasrows = 0 Then
txtTrackingNo.Text = ctrDate() & "-" & "000001"
Else
txtTrackingNo.Text = counter.CtrLastItemWithChar("ConcessionairesAccnt", "CSFNo", "CSFMaster", "WHERE (CSFNo LIKE '%" & ctrDate() & "%') ORDER BY CSFNo DESC", 5)
End If
dbCounter.CloseDB()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The Error is thrown here:
Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=#1", txtSeq.Text)
It Says:
System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed.
The Other Parts of the Sub Works fine, The part where I fetch Data on my MSSQL Server database. The Problem lies in the Access data-Fetching Code.
I tried Using the code on another project (just the code where i fetch access data) I worked on other solutions. But I copy and paste my code on any form in this solution I keeps giving the Error.
I thought Maybe I closed the connection somewhere but this is the only instance I used this code in this entire project. (Just to get the last reading record.)
The Database is in the correct place (C:\BILLSERV)
I've Tried searching it here on SE but all I can see where suggestions about maybe forgetting to open the connection. I used this code before and this code works on my other solutions. I just cant seem to have it work here on this particular project. I wonder Why..
I tried running another project using this code and it works fine.
Is there a bug about Access connection on VB.net 2012, I have been using this code (DBConnForAccess Class) for about a year now and this is the first time I have encountered this error. btw I use Access 2003 because this database used to be for an old system created in VB6.
Lastly could this be because the solution came from another computer using a VB.Net Program same as mine. Because We work as a team here. Hope someone with a better knowledge on these systems could help. Thanks in advance.
EDIT
If a connection has been made, there should be a .ldb file in access which should appear. (I tested this on another project and an ldb file appear once a connection has been made, as we all know ldb file contains the data of the user using the db file.) I tried to re-run the system and while I'm using the system no ldb file was created.
Also,I thought Maybe I closed the connection somewhere but this is the only instance I opened a connection in access and which I used the code in this entire project. (Just to get the last reading record.)
So this is NOT a duplicate of “There is already an open DataReader…” Reuse or Dispose DB Connections? Just for clarifications
After a week of debugging and reading articles in the web.
We have found the culprit of the Error.
Seems that the Target CPU Option in Advance compiler Settings was change to AnuCPU.
We noticed this after we checked the other application projects we used.
Changing it Back to x86 solves the connection problem.
I wonder why this affected the connection to the access.
All is working fine now. thank you Plutonix and Steve for all your suggestions we'll be having a change in our codes.

Command$() worked in Access 2007 but does not work in Access 2013

Items using:
Access 2013 Database Source is the .accdb (referenced as "Source")
Access 2013 Database .accde of the source. (referenced as "CurrentVersion")
The user has a copy of the CurrentVersion on their C:\AccessSystems folder (referenced as "UserVersion")
SQL Database table linked to "Source" named VersionControl2013.
Table contains: System_Name, Version_Number, MDE_Path_Name and MDE_Name.
The flow:
Developer makes a change in Source
Developer updates the Category to the next version number. Category is in the Databases properties.
Developer creates CurrentVersion and saves it to P:\ drive (where all the CurrentVersions are saved).
User opens UserVersion and code runs to check to see if it matches CurrentVersion.
User opts to update and code runs to close UserVersion and copy CurrentVersion to User's c:\AccessSystems folder.
Now... User is up to date with correct version.
UserVersion is opened by the user, on opening it checks to see if the version matches using below code:
Public Sub CheckVersionNumber()
Dim SQLConn As New ADODB.Connection
Dim AnswerSet As New ADODB.Recordset
Set dbs = CurrentDb
Set cnt = dbs.Containers!Databases
Set doc = cnt.documents!SummaryInfo
doc.Properties.Refresh
Set ThisVersion = doc.Properties("Category")
Set SystemName = doc.Properties("Title")
Set SQLConn = New ADODB.Connection
SQLConn.Provider = "sqloledb"
SQLConn.Open "Data Source=scgcserver1;Initial Catalog=SCGCDatawarehouse "
QueryString = "SELECT VersionControl2013.* FROM VersionControl2013 WHERE (((VersionControl2013.System_Name)=" & "'" & SystemName & "'" & "));"
AnswerSet.Open QueryString, SQLConn, , adCmdText
If AnswerSet.EOF = False Then
If RTrim(AnswerSet("Version_Number")) = ThisVersion Then
Else
MsgBox ("Version Number does not match")
ServDir = "p:\accesssytems"
Shell "MsAccess.exe " & "P:\AccessSystems\VersionControl\VersionControl2013.accde"
Application.Quit
End If
End If
AnswerSet.Close
With SQLConn
.Close
End With
End Sub
Note: The code below works in Access 2007. It will not work in Access 2013.
When CurrentVersion is called and opened it runs the code below:
Public Function LoadVersion()
DialogMessage = "You have a previous version of the Application, Do you want to UPDATE your version?"
DialogStyle = vbYesNo + vbDefaultButton1
DialogTitle = "Update Application"
DialogResponse = MsgBox(DialogMessage, DialogStyle, DialogTitle)
If DialogResponse = vbYes Then
ApplicationName = Command$()
Call GetApplicationInformation
DoCmd.Hourglass True
ToDirectory = "C:\AccessSystems\" & RTrim(DatabaseName)
FromDirectory = RTrim(MDEPathName) & RTrim(DatabaseName)
FileCopy "p:\AccessSystems\compiles\Access2013Compiles\" & DatabaseName, "c:\AccessSystems\" & DatabaseName
MsgBox ("Your Client Copy has been updated - Thank You " & " " & ApplicationName & " " & DatabaseName)
Shell "MsAccess.exe " & "C:\AccessSystems\" & RTrim(DatabaseName)
Application.Quit
End If
End Function
Public Sub GetApplicationInformation()
Dim SQLConn As New ADODB.Connection
Dim AnswerSet As New ADODB.Recordset
Set SQLConn = New ADODB.Connection
SQLConn.Provider = "sqloledb"
SQLConn.Open "Data Source=scgcserver1;Initial Catalog=SCGCDatawarehouse "
QueryString = "SELECT VersionControl2013.* FROM VersionControl2013 WHERE (((VersionControl2013.System_Name)=" & "'" & ApplicationName & "'" & "));"
AnswerSet.Open QueryString, SQLConn, , adCmdText
If AnswerSet.EOF = False Then
DatabaseName = AnswerSet("MDE_Name")
MDEPathName = AnswerSet("MDE_Path_Name")
End If
AnswerSet.Close
With SQLConn
.Close
End With
End Sub
I get a runtime error
52: Bad file name or number.
Debug takes it to line and DatabaseName is "".
FileCopy "p:\AccessSystems\compiles\Access2013Compiles\" & DatabaseName, "c:\AccessSystems\" & DatabaseName
I feel the line: ApplicationName = Command$() has something to do with it because ApplicationName is blank also. It is supposed to bring in the application's name.
Why does it work in 2007, but not in 2013?
That's a rather convoluted system you have there.
The Command() function returns a string that was appended to the Access command line with the /cmd switch.
You'd have to launch Access e.g. like this
"MSACCESS.EXE C:\mypath\Database1.accdb /cmd SomeString"
then if Database1.accdb calls Command(), it returns "SomeString".
But if I understand you correctly, the upper code launches the lower code with
Shell "MsAccess.exe " & "P:\AccessSystems\VersionControl\VersionControl2013.accde"
There is no /cmd switch, so Command() won't return anything.
Did it perhaps get lost in the switch to Access 2013?
EDIT:
As I wrote above, ApplicationName = Command$() cannot work in the lower code, because no /cmd string is passed here:
Shell "MsAccess.exe " & "P:\AccessSystems\VersionControl\VersionControl2013.accde"
It is used here:
WHERE VersionControl2013.System_Name = " & "'" & ApplicationName & "'"
so you need to pass whatever is the correct VersionControl2013.System_Name, like this:
Shell "MsAccess.exe " & "P:\AccessSystems\VersionControl\VersionControl2013.accde /cmd mySystemName"
Or if System_Name is simply the database (UserVersion) name, something like this:
Shell "MsAccess.exe " & "P:\AccessSystems\VersionControl\VersionControl2013.accde /cmd " & Dir(CurrentDb.Name)
I used Dir() to extract the file name from the full path.
Perhaps I am not seeing all the code or missing something but... normally you need to declare DatabaseName as a public variable available to all subroutines.
Or .. pass the values back to the calling statement.
Call like this:
databasename = GetApplicationInformation()
The function would look like this:
Public Function GetApplicationInformation() As String
...
GetApplicationInformation = AnswerSet("MDE_Name") ' the database name
But of course this does not explain why it worked in Access 2007. perhaps some more detail from you would help.