I've been handed an Access database with 3 columns: Name, category, e-mail. What I'm trying to do is get out, as strings, all of the e-mails that match a given category.
I have a slight understanding SQL as I'm in the process of learning it. I've managed to churn out this bit of code, which populates a visual grid with the first names
Dim comm As New OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=.\AddressBook.mdb")
Dim addda As New OleDbDataAdapter("SELECT FirstName FROM Contacts", comm)
Dim dd As New DataTable("Name")
addda.Fill(dd)
DataGridView2.DataSource = dd
So I feel I'm getting fairly close, but I can't figure out how to get that list of first names to go into a string (or array of strings). All of the online tutorials and books I find seem to go over just displaying the data in a dataview.
Point in the right direction?
try this:
Dim Names As New List(Of String)
Using comm As New OleDbConnection("Provider...")
comm.Open()
Using cmd As New OleDbCommand("SELECT FirstName FROM Contacts", comm)
Using reader As OleDbDataReader = cmd.ExecuteReader
While reader.Read
Names.Add(reader("FirstName").ToString)
End While
End Using
End Using
End Using
The Using format will automatically dispose of your data objects.
I'm sure LarsTech's response will work, but going back to your original example, you can always loop through your DataTable (dd), looking at the DataRow collection.
Dim Names As New List(Of String)
For Each R As DataRow In dd.Rows.Count
Names.Add(R.Item("FirstName").ToString)
Next
Then you can just check the count of Names and if it's greater than 0, iterate over that collection.
Related
My program uses a Database that is named (County Hunter - K8EMS.mdb) on my computer. What I want to do is use a variable that a user can enter on their screen and pick the DB to search on their computer ( County Hunter - "Variable".mdb). As every user has a different call where the variable will go.
This Database is created by another program used by the county hunter, all I want to do is search a table in this DB to see if a field is NULL or used. I have an input text box on the screen so they can enter their call and would like to use that input to finish naming the database to search, so hard coding and compiling wouldn't need to be done for every user.
I am using Visual Basic, in Microsoft visual studio 17.
Dim conn As OleDbConnection
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
Dim connString = "(Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Logger Data\County Hunter - " ' & mcall.text &'""' &.mdb&'"Jet OLEDB:Database.[County Hunter- (mcall,text.mdb) Password = ########;)"
The MDB is old Access database as the program that installed the database is in VB6. The connection string shows errors but I am fairly new to Access and I
need some direction on how to make this work.
Any ideas or help would be appreciated.
You could do this every time, but that would be a hassle. You can’t put it in the DB, because that is what you are locating...I would suggest putting it in the config file.
Dim config = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location)
Dim appSettings = CType(config.GetSection("appSettings"), AppSettingsSection)
Dim insensitive = StringComparison.CurrentCultureIgnoreCase
If (Not appSettings.AllKeys.Any(Function(key)
string.Compare(key, "name", insensitive) = 0)) Then
appSettings.Settings.Add("name", "bar")
config.Save()
End If
I cant find anything online to help.
I want to create a table if it doesnt already exist, or populate a listbox with what is stored in said table if it DOES exist. All I have so far is the populate and create table subroutines, but have no idea how to check the database so far.
Thank you
Checking if an MSAccess DATABASE exists or not is pretty simple because it is just a single file. So using File.Exists is enough
Suppose that your MDB file is
Dim accessFilePath = "D:\temp\myDatabase.mdb"
If File.Exists(accessFilePath) Then
... file exists
End if
Of course getting the content of the file (in terms of TABLES and QUERY) is a different thing and requires to open the connection and get the SCHEMA informations
Dim cnnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & accessFilePath
Using con = new OleDbConnection(cnnString)
con.Open()
Dim schema = con.GetSchema("Tables")
For Each row As DataRow in schema.Rows
Console.WriteLine(row.Field(Of String)("TABLE_NAME"))
Next
End Using
See how GetSchema works and what are its possible parameters and results
I'm trying to display my database on textboxes, with the help of the combobox for the ID. However, whenever I run my program, the error "Conversion from string "ID" to type integer is not valid" keeps on appearing. What should I do?
Private Sub FormAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb")
Dim reader As OleDb.OleDbDataReader
Try
cnn.Open()
Dim str As String = "select * from TableName"
command = New OleDb.OleDbCommand(str, cnn)
reader = command.ExecuteReader
While reader.Read
Dim sId = reader.GetName("ID")
ComboBox1.Items.Add(sId)
End While
cnn.Close()
Catch ex As OleDb.OleDbException
MessageBox.Show(ex.Message)
Finally
cnn.Dispose()
End Try
End Sub
Visual Basic says that the error is located here:
Dim sId = reader.GetName("ID")
Thank you so much!
Using ordinal positions are just plain evil. Why? First, it can cause your program to crash if you change the structure of the database in the future. Second, imaging you are returning 50 fields, and you are trying to debug the code six months from now, you'll have to start counting fields in your SELECT statement (If you EVER use ordinal notation, you simply must specify the fields so you know for sure the order.)
If you're going to use ordinal positions, then I would suggest you do something like
Dim sId = reader.GetName(reader.GetOrdinal("ID"))
The GetName() function takes an ordinal (integer) representing the column number from the result set. see here. You are passing in a string, hence the error. You want to call the GetValue() function with the column number instead.
In a VB.NET how can I loop through an an Access database without loading it to a DataGridView or loading it to a DataGridView and unload it after a comparison function finshed its work?
Using DataReader you can loop thru data, one row at a time without necessity of loading entire result set into DataTable/GridView.
Example usage (from http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader(v=vs.90).aspx)
Public Sub ReadData(ByVal connectionString As String, _
ByVal queryString As String)
Using connection As New OleDbConnection(connectionString)
Dim command As New OleDbCommand(queryString, connection)
connection.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
Console.WriteLine(reader(0).ToString())
End While
reader.Close()
End Using
End Sub
You pass connection string to your MS Access Database, and SELECT query to run. Example outputs data from the 1st column to console - but you can replace it with your own logic
Connect to the Access database.
Fetch the records using your SELECT… query.
Load the result into a List of your Custom class object (e.g: Customer) /Data Table /Data Set.
Write a loop (For / For Each) to iterate through each record and do the comparison with whatever you want to.
Try this yourself. If you encounter any errors, post that as a seperate question with relevant details.
I have a table in a Access Database that I'm loading into a VB.NET program, and I want a way to get the name of each of the columns into a list of Strings. Googling has shown that this is much easier with a SQL database, but that doing so in Access is much more difficult.
I came across this question Is there a query that will return all of the column names in a Microsoft Access table? Which gives a way to do it, but when I try the code it just populates my list with a bunch of "System.Collections.Generic.List'1[System.String]"
This is my adapted code. Any suggestions for a fix or a better way to do it?
Public Function GetColumns(ByRef database As String, ByRef table_name As String, ByRef columns As List(Of String)) As Integer
Dim com As OleDbConnection
Try
com = New OleDbConnection(database)
com.Open()
Catch ex As Exception
Return 1
End Try
Dim restrictions As String() = New String() {Nothing, Nothing, table_name, Nothing}
Dim dt As DataTable = com.GetSchema("Columns", restrictions)
com.Close()
For Each DR As DataRow In dt.Rows
columns.Add(DR("Column_Name").ToString)
Next
For Each holding As String In columns
Console.WriteLine(columns)
Next
End Function
Edit: Hah, I hate when I make stupid mistakes elsewhere in the function and it makes me think the meat of the function isn't working write. My for each loop isn't printing the right string. Should be Console.WriteLine(holding)
Console.WriteLine(columns)
change to:
Console.WriteLine(holding)
Then possibly kick yourself in the head for not spotting it =D ;-)
Try changing
For Each holding As String In columns
Console.WriteLine(columns)
Next
to
For Each holding As String In columns
Console.WriteLine(holding)
Next