Tell me if invalid SQL login, but continue with script... How? - sql-server-2008

I want my script to tell me, if the login to the database has failed with a custom response.write() and then continue with my script. Is this possible?
Say I have this:
set conn = server.createobject("adodb.connection")
dsn = "Provider = sqloledb; Data Source = XX; Initial Catalog = XX; User Id = XX; Password = XX
conn.connectiontimeout = 300
conn.commandtimeout = 300
if conn.state = 0 then
conn.open dsn
end if
If the conn couldn't be opened because of bad Data Source, User Id or Password, then I want it write me a message with response.write() and then CONTINUE with the rest of the script, or else it should do my sql-actions AND THEN continue :)

on error resume next
conn.open dsn
if err.number <> 0 then
response.write "connection string was bad"
else
' other SQL activity here
end if
on error goto 0

You can use On Error Resume Next
This page talks about handling connection errors and gives a pretty good example of what you are talking about.
http://www.codeguru.com/csharp/.net/net_general/debugginganderrorhandling/article.php/c19557/ASP-and-the-Error-Handler.htm

Related

Index was out of bound array exeption in Mysql

I have MySQL table for storing user details which contain 3 columns namely "UserName" ,"password" ,"Access Level". when i try to load details in to VB.net variables it shows " Index was out of bound arrray" Exeption
I am new to mysql please help
I have tried to change the index value of mysqldatareader()
DBConnectionMySql()
myCommandMySql.Connection = myConnectionMySql
myConnectionMySql.Open()
'-----
myCommandMySql.CommandText = "select * from tbl_userregistration where UserName = '" & Trim(Username_TextBox.Text) & "'"
myDataReaderMySql = myCommandMySql.ExecuteReader
If myDataReaderMySql.Read() = Nothing Then
MessageBox.Show("Invalide User Name you Enter!", "Username/Password checker", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Username_TextBox.Focus()
Else
If Username_TextBox.Text = myDataReaderMySql(1) And Password_TextBox.Text = myDataReaderMySql(2) Then
user = Username_TextBox.Text
username = Username_TextBox.Text
Weighing_frm.Show()
Me.Visible = False
Me.Refresh()
Else
MessageBox.Show("Invalide Username Or Password please check and Re-Login!", "Username/Password checker", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Username_TextBox.Focus()
when i try to log in in vb.net form from the loaded data "Index was outside the bounds of the array" error message was shown
Keep you data objects local so you can be sure they are closed and disposed. A Using...End Using block ensures this even if there is an error. You can make your connection string a form level variable so you can use it anywhere but that is the only form level variable you need.
You can pass your connection string directly to the constructor of the connection.
You can pass your sql command text and the connection directly to the constructor of the command.
Please always use Parameters. Not only will it save you from misplacing quotes but it will help ensure that correct datatypes are sent to the database. The most important thing is it helps protect you database from sql injection which can destroy your database. I had to guess at the datatypes in your database. Check the database and adjust the code accordingly.
The DataReader.Read method returns a Boolean so, checking if it returns Nothing is not a valid test. Boolean is a value type so it always returns True or False, never Nothing.
The username is always going to match because that is what you sent to the database in the where clause. As noted in comments by #Jimi, the indexes for the fields returned by the data reader start at 0 so, username would be 0, password 1 and, access level 2. Almost all collections in .net start at index 0.
Why are you using 2 different variables with the same value?
user = Username_TextBox.Text
username = Username_TextBox.Text
What is this supposed to do?
Me.Refresh()
In a real application you would NEVER store passwords as plain text. They would be salted and hashed.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using cn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand("select * from tbl_userregistration where UserName = #UserName;", cn)
cmd.Parameters.Add("#UserName", MySqlDbType.Text).Value = Trim(Username_TextBox.Text)
cn.Open()
Using dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If Password_TextBox.Text = myDataReaderMySql(1) Then
user = Username_TextBox.Text
Weighing_frm.Show()
Me.Visible = False
Else
MessageBox.Show("Invalide Username Or Password please check and Re-Login!", "Username/Password checker", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Username_TextBox.Focus()
End If
Else
MessageBox.Show("Invalid User Name you Enter!", "Username/Password checker", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Username_TextBox.Focus()
End If
End Using
End Using
End Using
End Sub

MS Access ADO connection string with Failover Partner option

Is it possible to use an ADO connection string in VBA Access with failover partner option included?
My connection code looks something like this:
Public Function OpenADOConnection() As Boolean
On Error GoTo err_trap
' Opens Global ADO Connection if it isnt already open.
' Returns TRUE if connected
Dim boolState As Boolean
If gcnn Is Nothing Then
Set gcnn = New ADODB.Connection ' if the global has not been instantiated or has been destroyed
End If
If gcnn.state = adStateOpen Then
boolState = True ' already open, nothing else to do
Else
gcnn.ConnectionString = "Data Source=SQL01;Failover Partner=SQL02;Initial Catalog=DBNAME;Integrated Security=True"
gcnn.Open
If gcnn.state = adStateOpen Then
boolState = True
Else
boolState = False ' cannot open connection so return false
End If
End If
OpenADOConnection = boolState ' return the connection state
exit_here:
Exit Function
err_trap:
OpenADOConnection = False
Call MsgBox("Unable to connect to the database. Please notify Database Administrator!" & vbCrLf & _
"(This error CANNOT be logged!", vbCritical, "ADO Connection Failed:", "", 0)
200 Resume exit_here
End Function
Currently, it fails to open the connection so I'm not sure what I'm missing or even if it's possible to achieve this.
Essentially I want the connection to automatically failover without user interference and knowledge.
I don't see the Provider being defined anywhere in your connection string. That is a general problem.
I never used the failover options with ADO, but I'm pretty sure the old OLE DB Provider (SQLOLEDB) does not support them. Instead you should use the brand new Microsoft OLE DB Driver for SQL Server (msoledbsql).

How can I get the connection string in vba from the linked tables in access 2013?

I have this linked tables on my access and I want to get the connection of it
Here is the screenshot
In my vba I tried this code but does not work because my stored procedure does not execute
Dim adocmd As New ADODB.Command
DoCmd.Maximize
adocmd.ActiveConnection = Application.CurrentProject.Connection.ConnectionString
adocmd.CommandType = adCmdStoredProc
adocmd.CommandText = "spr_DECSBillingSchedule"
adocmd.CommandTimeout = 0
On Error Resume Next
adocmd.Execute , , adExecuteNoRecords
Set adocmd = Nothing
On Error GoTo 0
How can I possibly fix this issue? thanks!
The definitions for tables are stored in a system table called MSysObjects, the connection string is in field Connect. You can access this table to get the connection string as and when you want to run the sproc (you'll need to reference a table you know is in the same database, I have front ends linked to multiple databases), though as the connection string does not change you may be better to set it to a global variable or just hard code it in (which i have fallen into the habit of doing).
NOTE: This is as per MS Access 2007, it is the only one I have installed
Below is an example of a function I use to execute a sproc, the sproc returns a value to confirm it has completed successfully, which is returned in #Ret. Hope this helps.
Function LogImportFile(strFile As String) As Long
On Error GoTo Err_Handle_LogImportFile
Set cnn = CreateObject("ADODB.Connection")
cnn.ConnectionString = "DRIVER={SQL Server};SERVER=[Server];DATABASE= _
[DatabaseName];Trusted_Connection=Yes"
' The above is for linking to a SQL Server table using a DSN less connection
' which I would highly recommend (DSN less) if you plan to distribute your
' database
cnn.Open cnn.ConnectionString
Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = cnn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "cmsUser.usp_LogImportFile"
cmd.CommandTimeout = 0
Set param = cmd.CreateParameter("#FileName", adVarChar, adParamInput, _
200, strFile)
cmd.Parameters.Append param
Set param = cmd.CreateParameter("#Ret", adInteger, adParamOutput)
cmd.Parameters.Append param
cmd.Execute
LogImportFile = cmd.Parameters("#Ret")
Exit_Proc:
Set cnn = Nothing
Set cmd = Nothing
Set param = Nothing
Exit Function
Err_Handle_LogImportFile:
Msgbox "LogImportFile - " & Err.Number & " - " & Err.Description
LogImportFile = -1
GoTo Exit_Proc
End Function

Changing a user Password in vb.net

So i am trying to change the password of a user in my vb.net project that i been working on. but everytime i run my code i get me catch "Something went wrong". i can't figur out why. i am using a MYSQL database. can anybody help me?
Try
reader = cmd.ExecuteReader()
Dim found As Boolean = False
Do While reader.Read()
If username = DirectCast(reader("username"), String) Then
If password = DirectCast(reader("password"), String) Then
found = True
Else
MessageBox.Show("username and password do not match")
End If
End If
If found = True Then
Dim cmd2 As New MySqlCommand
Dim insertStatment As String = "UPDATE login set password = '" +
newpassword + "' where username = '" + username + "'" , con)
cmd2.ExecuteNonQuery()
MessageBox.Show("password change successfully")
'End If
End If
Loop
Catch
MessageBox.Show("Something went wrong")
You should avoid to use string concatenation to build sql statements. Doing in this way leads the path to errors like when you have a username/password with single quote characters or worst if you have a smart and malicious user that writes something like this in your input textboxes
So you should write
Dim insertStatment As String = "UPDATE login set password = #p1 where username = #p2"
Dim cmd2 As New MySqlCommand(insertStatment, con)
cmd2.Parameters.AddWithValue("#p1", password)
cmd2.Parameters.AddWithValue("#p2", username)
cmd2.ExecuteNonQuery()
Another possible cause of your error is the handling of the MySqlConnection. In your code there is no Open of the connection, so I assume that it is open, but this leads to another problem of your code:
Do not catch exception and then print unusable error message.
If you really want to give a message try to print the error message given in the exception
Catch e As Exception
MessageBox.Show("Something went wrong: " & Environment.NewLine & e.Message)
This will give a pretty clear message that explains what the problem is.

Should app invoked by shortcut to network drive .EXE avoid JET related errors over wifi network?

I have a problem with a VB6 app using a Access-MDB database.
A customer has the .MDB and app .EXE located on a network drive over a wifi network. On one of the workstations, when the app is invoked by a shortcut to the .EXE on the network drive there are no errors, but when the app is installed and run locally on the workstation (with the .MDB remaining on the network drive) there is an error.
Here is the relevant part of the code. The error message reported is "Unable to update at this time. Try again later."
Private Sub UpdateHistory()
Dim ecnt As Integer
Dim bInTrans As Boolean
On Error GoTo HistErr
bInTrans = False
ecnt = 0
Randomize
DBEngine.SetOption dbLockDelay, 90 + Rnd * 60
DBEngine.Idle dbRefreshCache
SWWorkspace.BeginTrans
If action = 1 Then
historyfile.AddNew
historyfile("customerid") = gblpkey
historyfile("operatorid") = CurrentOperator
historyfile("type") = gbltype
historyfile("date") = Format(Now, "dd/mm/yyyy hh:mm:ss")
If gbltype = 1 Or gbltype = 2 Or gbltype = 6 Then
historyfile("rtype") = "Manual"
End If
Else
historyfile.Edit
End If
saveDate = historyfile("date")
historyfile("memo") = ptext
historyfile.Update
SWWorkspace.CommitTrans dbForceOSFlush
bInTrans = False
Exit Sub
HistErr:
ecnt = ecnt + 1
If ecnt > 10 Then
If bInTrans Then
SWWorkspace.Rollback
bInTrans = False
End If
Screen.MousePointer = vbDefault
MsgBox "Unable to update at this time. Try again later. "
Exit Sub
End If
sleep 1
DBEngine.Idle dbRefreshCache
Resume
End Sub
You need to catch the real error. ATM the only error msg you told us is the custom error msg from the app "Unable to update at this time. Try again later." ....which is a catch all error msg after 10 error retries.
The problem disappeared when I placed the EXE on the network drive and put a shortcut to it on the other workstation. I can only assume that invoking an EXE via a shortcut to a network location plays some part in preventing a wifi connection dropping out when accessing an MDB.