Dim con As New OleDb.OleDbConnection
Sub connecttodatabase(ByVal fileselected As String)
Dim databasepassword
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = " & fileselected
Try
con.Open()
Catch e As OleDb.OleDbException
If e.Message = "Not a valid password." Then
Console.WriteLine("Database has a password. Please enter password to continue.")
databasepassword = Console.ReadLine()
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = " & fileselected & ";JetOLEDB:Database Password=" & databasepassword & ";"
con.Open()
End If
errorid = 1
Finally
End Try
End Sub
The error I am encountering occurs at the second con.Open() when I try to connect to a .mdb database file which I created in access, the function correctly tells me I have a password, but then once I enter my password I get the error defined in the title, and I have no idea why. Any help would be greatly appreciated.
Try this instead:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;User Id=admin;Password=YOURPASS;
Also, what exception are you getting from the first call to open the db? Maybe it's same problem: the ISAM isn't present. Try reinstalling MDAC:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=78cac895-efc2-4f8e-a9e0-3a1afbd5922e
Related
I'm trying to automate the import of csv data into sql. All files, but one are imported ok, so there is no issue with the code. This particular file has a mixed data type column. And when importing data, it loads data as Double, instead of String. As a result, the values that have words, are imported as null. I tried to convert that column into String (ds.Tables(0).Columns(4).DataType), but it makes no difference. When I try to check the type right after the conversion attempt, it shows runtime type, not a string. I have spent a few days researching similar issues and tried everything I could find. Hopefully someone here can offer help on converting the column properly, as it doesn't work for me. Please see the code below. Thanks!
Private Sub ImportIntoSqlBulk(SqlConnString As SqlConnection, ConnStringSql As String, TableNameSql As String, Filenmcsv As String)
SqlConnString.ConnectionString = ConnStringSql
SqlConnString.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SqlConnString)
bulkCopy.DestinationTableName = TableNameSql
Try
bulkCopy.WriteToServer(GetCsvData(PathImpt, Filenmcsv))
SqlConnString.Close()
Catch ex As Exception
Email_Subject = "Financial Data Import from Excel Error"
successflag = "N"
Email_Body = "There was an error importing data into " & TableNameSql & " from excel. Error message: " & ex.Message
Send_Email()
SqlConnString.Close()
Exit Sub
End Try
End Using
End Sub
Public Function GetCsvData(ByVal strFolderPath As String, ByVal strFileName As String) As DataTable
Dim strConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFolderPath & ";Extended Properties=""Text;HDR=YES;IMEX=1"""
Dim strConnString2 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFolderPath & ";Extended Properties=""Text;HDR=YES;IMEX=1;MaxScanRows=0"""
Dim conn2 As New OleDbConnection(strConnString2)
Dim conn As New OleDbConnection(strConnString)
Try
conn.Open()
Dim cmd As New OleDbCommand("SELECT * FROM [" & strFileName & "]", conn)
Dim da As New OleDbDataAdapter()
da.SelectCommand = cmd
Dim ds As New DataSet()
da.Fill(ds)
If strFileName = "CheckRegister.csv" Then
Convert.ToString(ds.Tables(0).Columns(4).DataType)
ds.Tables(0).Columns(4).DataType.GetType()
End If
da.Dispose()
Return ds.Tables(0)
Catch ex As Exception
Return Nothing
Finally
conn.Close()
End Try
End Function
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...
When I am trying to compact my Access 2010 database (no password), I am getting the error message Class Not Registered I am using Visual Studio 2010, and I have not idea what this problem is. Here Is the code i'm using:
Private Sub Compactdb()
Dim JRO As JRO.JetEngine
JRO = New JRO.JetEngine
'The first source is the original, the second is the compacted database under an other name.
JRO.CompactDatabase("Provider=Microsoft.Jet.OLEDB.5.0;Data Source=C:\Forte\Ex.mdb; Jet OLEDB:Engine Type=5", "Provider=Microsoft.Jet.OLEDB.5.0;Data Source=C:\Forte\Temp.mdb; JetOLEDB:Engine Type=5")
'Original (not compacted database is deleted)
System.IO.File.Delete("C:\Forte\Ex.mdb")
'Compacted database is renamed to the original databas's neme.
Rename("C:\Forte\Temp.mdb", "C:\Forte\Ex.mdb")
'User notification
MsgBox("The database was compacted successfully")
End Sub
If I change the Jet.OLEDB.5.0 to 4.0 I get a different error message of Unrecognized databse format
Try
Dim ParentCNN As String
Dim CloneCNN As String
Dim JrO As New JRO.JetEngine
ParentCNN = "PROVIDER = MICROSOFT.ACE.OLEDB.12.0;DATA SOURCE = C:\Forte\Fortedb.accdb;JET OLEDB:DATABASE PASSWORD = 21061975;"
CloneCNN = "PROVIDER = MICROSOFT.ACE.OLEDB.12.0;DATA SOURCE = C:\Forte\Temp.accdb;JET OLEDB:DATABASE PASSWORD = 21061975;Jet OLEDB:Engine Type=5"
'If cnnMDE.State = ConnectionState.Open Then
' cnnMDE.Close()
'End If
JrO.CompactDatabase(ParentCNN, CloneCNN)
If System.IO.File.Exists("C:\Forte\Temp.accdb") Then
System.IO.File.Delete("C:\Forte\Fortedb.accdb")
Rename("C:\Forte\Temp.accdb", "C:\Forte\Fortedb.accdb")
End If
Catch ex As Exception
MainTextBox.AppendText(Environment.NewLine & "Database Compression Failure :" & vbCr & ex.Message)
End Try
I am creating a custom log in page using VB in Visual Studio. Every time I try logging in, however, I get the following error:
"Incorrect syntax near '.'".
When I put in the wrong username/password combo it recognizes this, but when it is right it will get this error and fail to log in.
Private Function VerifyLogin(ByVal UserName As String) As Boolean
Try
Dim cnn As New Data.SqlClient.SqlConnection
cnn.ConnectionString = My.MySettings.Default.RedwoodConnectionString.Replace(";Integrated Security=True", ";Integrated Security=False") & UserSetting
Dim cmd As New Data.SqlClient.SqlCommand
cmd.Connection = cnn
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT COUNT (principal_id) FROM _ sys.database_principals WHERE(name = '" & UserName & "')"
cnn.Open()
Dim i As Integer
i = cmd.ExecuteScalar()
cnn.Close()
If (i > 0) Then Return True
Return False
Catch ex As Exception
System.Windows.Forms.MessageBox.Show("Error: " & ex.Message & vbNewLine & "Location: VerifyLogin() in Login.vb" & vbNewLine & "Returned value: False")
Return False
End Try
End Function
Look at this portion of your sql:
FROM _ sys.database_principals
See the mistake there? It thinks the _ is the full table name and sys is an alias. At this point, .database_principals is no longer valid, hence your error.
And while we're at it, you really need to fix the sql injection vulnerability!!
Im new to visual basic.. I would like to ask on how to fixed the problem "Could not find installable ISAM.". I used Visual Basic as programming language. I used MS access as the database. My program is to fetch data from access. This would be my code.
Imports System.Data.OleDb
Module Main
Dim mDataPath As String
Sub Main()
GetPupils()
Console.ReadLine()
End Sub
Private Function GetConnection() As OleDb.OleDbConnection
'return a new connection to the database5
Return New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Database Password=oNer00FooR3n0 " & "Data Source=" & "C:\Users\ERICO YAN\Desktop\MSaccessDB\MSaccessDB\oneroofccp.mdb")
End Function
Public Function GetPupils() As DataSet
Dim conn As OleDb.OleDbConnection = GetConnection()
Try
Dim ds As New DataSet 'temporary storage
Dim sql As String = "select * from SESSIONS" 'query
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql, conn) 'connection
Try
da.Fill(ds, "SESSIONS") 'fetch data from db
Finally
da.Dispose() 'in case something goes wrong
End Try
Dim startVal = 0 'first record
Dim endVal = ds.Tables(0).Rows.Count 'total number records
For var = startVal To endVal - 1 'display records
Console.WriteLine(ds.Tables(0).Rows(var).Item(0).ToString() + " " + ds.Tables(0).Rows(var).Item(1).ToString() + " " + ds.Tables(0).Rows(var).Item(3).ToString() + " " + ds.Tables(0).Rows(var).Item(3).ToString()) 'code for display id and name
Next
Return ds
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Module
I would like to know what is the cause of the error so that I can proceed to my program.. Thank you so much for the feedback..
You seem to be missing a delimiter after your password attribute.
I think you also need to use Jet OLEDB:Database Password=... instead (if indeed you have an access database protected with a password):
"Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & "C:\Users\ERICO YAN\Desktop\MSaccessDB\MSaccessDB\oneroofccp.mdb;" _
& "Jet OLEDB:Database Password=oNer00FooR3n0;"
Missing ; delimiter here:
...Password=oNer00FooR3n0 " & "Data Sourc...
Needs to be
...Password=oNer00FooR3n0 " & ";Data Sourc...
Also just Password instead of Database Password.
Initially, i too got this sort of error, but when i wrote the connection string in a single line (i mean without using [& _] or breaking in 2 lines, then this worked properly.
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\USER1\Desktop\MSaccessDB\MSaccessDB\my_database_file.mdb;Database Password=MyPassword"
Hope this helps.
Mukesh L.