I have a class that's handling my connection to an Access 2003 database. I would like to setup the same thing only for Access 07/10 .accdb files. Any help is appreciated! Thank you!
Here's a list of my references and a copy of the class object
References:
Microsoft Access 14.0 Object Library
Microsoft DAO 3.6 Object Library
ConnectionClass:
Option Explicit
Private Const DbFile = "\\server\folders\Report.mdb"
Dim OpenConn As DAO.Database
Dim ObjAccess As Object
Private Sub Class_Initialize()
On Error Resume Next
Set OpenConn = DAO.OpenDatabase(DbFile)
If Err.Number = 3024 Then MsgBox "Check connection string in the VBA StaticClass object", vbOKOnly
Set ObjAccess = CreateObject("Access.Application")
ObjAccess.Visible = False
ObjAccess.OpenCurrentDatabase (DbFile)
End Sub
Public Function runSQL(ByVal sql As String) As Recordset
Set runSQL = OpenConn.OpenRecordset(sql)
End Function
Public Function runVolumeReport(ByVal inMacro As String)
ObjAccess.DoCmd.RunMacro inMacro
End Function
Public Function closeResources()
Set ObjAccess = Nothing
OpenConn.Close
End Function
There is an issue in Class_Initialize.
On Error Resume Next
Set OpenConn = DAO.OpenDatabase(DbFile)
If Err.Number = 3024 Then MsgBox "Check connection string in the VBA StaticClass object", vbOKOnly
Because of On Error Resume Next, any error other than 3024 ("Could not find file") will pass silently and OpenConn will not be set as you intend. Later when you attempt to use OpenConn, you will trigger another error. And, in a comment, you reported you do get another error with this line:
Set runSQL = OpenConn.OpenRecordset(sql)
Unfortunately, due to On Error Resume Next, we don't know why OpenDatabase failed leaving OpenConn unset. Since ObjAccess seems to work as an Access application object, you could try setting OpenConn to ObjAccess.CurrentDb.
Private Sub Class_Initialize()
Set ObjAccess = CreateObject("Access.Application")
ObjAccess.Visible = False
ObjAccess.OpenCurrentDatabase DbFile
Set OpenConn = ObjAccess.CurrentDb
End Sub
OTOH, you may be able to dispense with OpenConn entirely if you change your runSQL function like this ...
Public Function runSQL(ByVal sql As String) As Recordset
'Set runSQL = OpenConn.OpenRecordset(sql) '
Set runSQL = ObjAccess.CurrentDb.OpenRecordset(sql)
End Function
One way to open a accdb (SQL Server) table is this:
Dim cmd As New ADODB.Command
Dim rs As ADODB.Recordset
Dim strSQL As String
strSQL = "select SomeStuff from SomeTable"
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandText = strSQL ' you can put in the SQL directly,
' but I find the string easier to manipulate away from the .CommandText
Set rs = cmd.Execute
My References (Access 2010):
I think the critical one you would need to add would be the Microsoft ActiveX Data Objects X.X Library
Imports System.Data.OleDb
Public Class Form1
Dim strSQL As String
Dim ds As New DataSet
Dim strConnection As String
Dim DBconnection As New OleDbConnection
Dim oledbAdapter As New OleDbDataAdapter
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Informatica\April - Juni\Acces\db-games.accdb"
DBconnection = New OleDbConnection(strConnection)
strSQL = "SELECT * from tbl_games"
Try
DBconnection.Open()
oledbAdapter = New OleDbDataAdapter(strSQL, DBconnection)
oledbAdapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
DBconnection.Close()
End Sub
End Class
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Informatica\Acces\db_Games.accdb;Persist Security Info=False")
Dim cmd As New OleDbCommand
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO tbl_gerne(Omschrijving) VALUES('adventure')"
cmd.ExecuteNonQuery()
con.Close()
Related
I am trying to simplify my code, having a module which contains all DB connection functions in one Access, so this is what I've already done:
Module "DB"
Public Function connect() As String
Dim cn As ADODB.connection
cn.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;Initial Catalog=system;Data Source=localhost; User Id= root;Password= root;"
connect = cn
End Function
Public Function sql(cn As String, query As String) As String
Dim rs As ADODB.Recordset
cn.Open
Set rs = cn.Execute(query)
cn.Close
sql = rs
End Function
Event when I click in a button
Private Sub btn_run_Click()
conexao = connect()
result = sql(conexao, "SELECT TOP 1* FROM MIS.MP_BASE_ACOES")
End Sub
Here is what my Access as an error:
Translating to en -> "Compilation error: The type defined by the user wasn't defined"
What am I doing wrong? Is that the correct way to define a connection function?
PS: There's no error in ConnectionString, I just changed some content because it is confidential.
Edit1: Following FunThomas, I really have forgotten to mark all the references like ActiveX from my project, but it still not working, now with this error:
"Uncompatible argument ByRef"
In general, you code has the following errors:
Wrong usage of functions (Public Function connect() As String)
The SQL function is not called
The object cn is of type string, and thus it does not have the Execute procedure.
Try this and try to assign the TestMe to a button. The idea to give the ConnectionString as a separate Function is a good one:
Option Explicit
Public Function ConnectionString() As String
ConnectionString = "Provider=SQLOLEDB; Data Source=1111111111; Database=ABC; User ID=NotSA; Password=NotTheSaPwd"
End Function
Public Sub TestMe()
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open (ConnectionString)
rs.Open "SELECT * FROM TABLE", cn
Do While Not rs.EOF
Debug.Print rs!ColumnName
rs.MoveNext
Loop
End Sub
Currently you are passing a string when your function requires a connection object. Simply change parameter types accordingly:
Public Function sql(cn As ADODB.connection, query As String) As String
Dim rs As ADODB.Recordset
cn.Open
Set rs = cn.Execute(query)
cn.Close
sql = rs
End Function
I have a program that takes info from the user and logs them into a database using Phpmyadmin, our code is the exact same, except for my friend he can't login.
Code is here:
Both our database name, tables and columns are the EXACT same, he can register the account to the DB so it stores it, but when he tries to login with the same information it says that it was unsuccessful.
SignUpForm(THIS WORKS)
Public Class frmSignup
Dim ServerString As String = "Server=localhost;User Id=root;Password=;Database=accountinfo"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MsgBox("Successfully connected to DB")
Else
SQLConnection.Close()
MsgBox("Failed to connect to DB")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveAccountInformation(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
SQLConnection.Dispose()
End Sub
Private Sub btnSignup_Click(sender As Object, e As EventArgs) Handles btnSignup.Click
If txtPasswd.Text = txtPasswd2.Text Then
MessageBox.Show("Passwords Match!")
Dim HashedPass As String = ""
'Converts the Password into bytes, computes the hash of those bytes, and then converts them into a Base64 string
Using MD5hash As MD5 = MD5.Create()
HashedPass = System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(txtPasswd.Text)))
End Using
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & "','" & HashedPass & "')"
SaveAccountInformation(SQLStatement)
MessageBox.Show("Account Successfully Registered")
frmLogin.Show()
frmLoginScreen.Hide()
Else
MessageBox.Show("Passwords Do Not Match!")
txtPasswd.Text = Focus()
txtPasswd.Clear()
txtPasswd2.Text = Focus()
txtPasswd2.Clear()
End If
End Sub
End Class
LOGIN FORM(THIS DOES NOT WORK FOR HIM BUT IT WORKS FOR ME)
Imports MySql.Data.MySqlClient
Imports System.Security.Cryptography
Public Class frmLogin
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim conStr = "Server=localhost;User Id=root;Password=;Database=accountinfo"
Dim SQL = "SELECT * FROM accountinfodb WHERE Usernames = #uname AND `Passwords` = #pword"
Dim HashedPass As String = ""
'Converts the Password into bytes, computes the hash of those bytes, and then converts them into a Base64 string
Using MD5hash As MD5 = MD5.Create()
HashedPass = System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(txtPasswd.Text)))
End Using
' this object will be closed and dispose # End Using
Using dbCon As New MySqlConnection(conStr)
' the command object likewise
Using cmd As New MySqlCommand(SQL, dbCon)
dbCon.Open()
cmd.Parameters.Add(New MySqlParameter("#uname", txtUsername.Text))
cmd.Parameters.Add(New MySqlParameter("#pword", HashedPass))
' create a Using scope block for the reader
Using rdr As MySqlDataReader = cmd.ExecuteReader
If rdr.HasRows Then
MessageBox.Show("Welcome, " & txtUsername.Text)
frmProduct.Show()
Else
MessageBox.Show("Oops! Login unsuccessful!(Password/Username may be wrong, or the user may not exist!")
txtUsername.Clear()
txtUsername.Focus()
txtPasswd.Clear()
End If
End Using
End Using ' close/dispose command
End Using ' close/dispose connection
End Sub
End Class
WOULD ALSO LIKE TO MENTION
I shared my files over google drive with him, so he did not copy and paste any of the code. This is the exact same files from MY computer.
Ok I found the issue, he was using an outdated version of MySQL while my version was the most up to date. I reinstalled the proper MySQL server to the newest version and it worked!
I am trying to access MySql database but get this error:
Exception thrown: 'System.InvalidOperationException' in MySql.Data.dll
Additional information: The CommandText property has not been properly initialized.
This Would be my Code
Imports MySql.Data.MySqlClient
Public Class Login
Dim cn As New MySqlConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cn.ConnectionString = "server=localhost; userid=root; password=root; database=pos"
cn.Open()
MsgBox("Connected")
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
cn.Close()
Dim myadapter As New MySqlDataAdapter
Dim sqlquery = "SELECT * from pos.values where username='" & txtUsername.Text & "' AND password='" & txtPassword.Text & "'"
Dim mycommand As New MySqlCommand
mycommand.Connection = cn
cn.Open()
myadapter.SelectCommand = mycommand
Dim mydata As MySqlDataReader
mydata = mycommand.ExecuteReader
If mydata.HasRows = 0 Then
Beep()
MsgBox(txtUsername.Text & " Invalid")
Else
MsgBox("Welcome " & txtUsername.Text)
MainWindow.Show()
Me.Hide()
cn.Close()
End If
End Sub
End Class
Just like the error says, you never set the CommandText property of the MySqlCommand object. You've defined a SELECT query, but never use it anywhere. Set it on the command object before trying to use that object:
mycommand.CommandText = sqlquery
Note: Be aware that your code is wide open to SQL injection attacks. You should use query parameters instead of directly executing user input as code. Basically, you're allowing users to execute any code they want on your database.
Also: You are storing user passwords in plain text. This is grossly irresponsible to your users. If you can read their password, so can an attacker. User passwords should be obscured with a 1-way hash so that they can never be read, not even by you as the system owner.
I try to save the "path" on MYSQL database but I get the error
the datatype of photo is BLOB
database is imageupload
table is student
hope someone can help me to fix my error and order to save the path on database
thanks a lot more power to us!!!
My error is that
"The connection cannot be used to perform this operation. It is either closed or invalid in this context."
My connection in module
Module Module1
Public cn As New ADODB.Connection
Public rs As New ADODB.Recordset
Sub konek()
With cn
.ConnectionString = "DRIVER={MY SQL ODBC 5.1 driver};SERVER=localhost;PWD=;UID=root;database=imageupload"
End With
End Sub
End Module
======================================================================
My form in Visual Basic 2010
Public Class Form1
Private Sub btnbrowsepic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnbrowsepic.Click
OpenFileDialog1.FileName = ""
With OpenFileDialog1
.InitialDirectory = "C:\"
.Filter = "All Files|*.*|Bitmaps|*.bmp|GIFs|*.gif|JPEGs|*.jpg"
.FilterIndex = 2
End With
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
With PictureBox1
.Image = Image.FromFile(Me.OpenFileDialog1.FileName)
.SizeMode = PictureBoxSizeMode.StretchImage
End With
End If
Me.lblpath.Text = Me.OpenFileDialog1.FileName.ToString
End Sub
Private Sub btnsavepic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsavepic.Click
rs = New ADODB.Recordset
rs.Open("select * from student", cn, 3, 3)----- error is here when i save the path on my database
With rs
.AddNew()
.Fields("photo").Value = "" & lblpath.Text
.Update()
MsgBox("Data has been saved")
End With
End Sub
End Class
How can I write a sql query that takes information from a database, and then put in the text in a label? I'm not really sure how to do this.
MSDN has lots of examples of getting data via ADO.NET. E.g. http://msdn.microsoft.com/library/dw70f090.
You will need to adjust the connection and command types (and the connection string) to be correct for My SQL. If you have ODBC drivers for My SQL then you can follow the ODBC example with just a change of connection string.
For using MySQL with .NET I'd recommend you this tutorial, and for your problem specially part 6, about reading the data with a MySQLDataReader.
An (almost working) sample by copy&paste from there with some changes:
Private Sub getData()
Dim conn As New MySqlConnection
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
Dim SQL As String
SQL = "SELECT LabelContent FROM myTable"
conn.ConnectionString = myConnString ' your connection string here'
Try
conn.Open()
Try
myCommand.Connection = conn
myCommand.CommandText = SQL
myReader = myCommand.ExecuteReader
' loop through all records'
While myReader.Read
Dim myLabelValue as String
myLabelValue = myReader.GetString(myReader.GetOrdinal("LabelContent"))
' ... do something with the value, e.g. assign to label '
End While
Catch myerror As MySqlException
MsgBox("There was an error reading from the database: " & myerror.Message)
End Try
Catch myerror As MySqlException
MessageBox.Show("Error connecting to the database: " & myerror.Message)
Finally
If conn.State <> ConnectionState.Closed Then conn.Close()
End Try
End Sub
For selecting one column to label from ms access 2007 database just follow this step
Create ms access database for example i make name "test.accdb" and make 1 column for example column name is "ColumnName" and one table with name "Table1"
save it on whatever folder
open vb 2008 and make one form
import adodb on first writing
write this code inside class
Sub lihat()
Dim str As String = "select * from Table1"
Dim cn As New OleDb.OleDbConnection
Dim com As New OleDb.OleDbCommand
Dim adp As OleDb.OleDbDataReader
With cn
.ConnectionString = "Provider=Microsoft.ace.oledb.12.0;data source=test.accdb;persist security info=false"
.Open()
End With
With com
.Connection = cn
.CommandText = str
End With
adp = com.ExecuteReader
adp.Read()
Label1.Text = adp(1)
cn.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
lihat()
End Sub
number 1 on adp(1) is number of column on Table1.