I'm trying to create a reminder that notifies users the number of days before a chemical expires. I'm trying to retrieve the data in my database using ForEach loop, but I can't get the syntax right.
For Each chemicalName as DataRow In chemicalinventory.Rows
For some reason, the error: name 'chemicalinventory' not declared keeps popping up.
From what I seen online, that is supposed to be the table name. Am I coding it wrong? Please answer if you know what's the error.
You cannot just directly start querying tables in this manner. You need to select your data from the database table and use it to fill a DataTable. You can then loop through the rows of this DataTable to get what you're after.
There are many ways to do that, but here is a very basic setup - granted, you'd need to specify a connection string in your Web.Config, and modify the SQL query to be relative to your needs.
Dim sqlConnection1 As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("YOUR_CONNECTION_STRING").ConnectionString)
Dim cmd As New SqlCommand
cmd.CommandType = Data.CommandType.Text
cmd.CommandText = "SELECT * FROM chemicals"
cmd.Connection = sqlConnection1
Dim DataAdapter As New SqlDataAdapter
DataAdapter.SelectCommand = cmd
Dim chemicalInventory As New DataTable()
DataAdapter.Fill(chemicalInventory)
For each row as DataRow in chemicalInventory.rows
Response.write(row.item("column_name"))
Next
Related
I pull from my MySQL database, and fill it using a MySQLDataAdapter. MasterDataTable is my class level DT.
Dim SQLstring As String = "SELECT * FROM Inventory.Metadata"
Using cmdSel As New MySqlCommand(SQLstring, MySQLconn.conn)
Dim da As New MySqlDataAdapter(cmdSel)
da.Fill(MasterDataTable)
End Using
Somebody updates the MySQL database, and I want to refresh the data again.
MasterDataTable.Clear()
Dim SQLstring As String = "SELECT * FROM Inventory.Metadata"
Using cmdSel As New MySqlCommand(SQLstring, MySQLconn.conn)
Dim da As New MySqlDataAdapter(cmdSel)
da.Fill(MasterDataTable)
End Using
The problem is, if the user has something selected, it will clear their selection.
Obviously this clears the datatable and re-fills it. Is there any way to accomplish the same task without MasterDataTable.clear?
Used jmcilhinney's suggestion, created a separate table, compared the two, and deleted from main table if it didn't exist in the other.
Thanks :)
I am doing some assignments at school where we are supposed to connect to a database using VB.NET, but my SQL queries does not do what they are supposed to do.
tilkobling.Open()
Dim sql As New MySqlCommand("SELECT * FROM personer WHERE fornavn='#navn';", tilkobling)
sql.Parameters.AddWithValue("#name", TextBox1.Text)
Dim da As New MySqlDataAdapter
Dim intern_tabell As New DataTable
da.SelectCommand = sql
da.Fill(intern_tabell)
tilkobling.Close()
I have tried hardcoding the SQL queries with 'william', my own name and a name that I know for sure is in the database, but both the parameterized and the hardcoded option does nothing, not even an error.
I'm also using this SQL query in my code: Dim sql As New MySqlCommand("SELECT * FROM personer ORDER BY #row;", tilkobling), but that seems to ignore my ORDER BY command, and executes only the SELECT command; again, without errors.
EDIT:
After populating the DataTable, I add all the rows from the DataTable to a ListBox.
For Each rad As DataRow In intern_tabell.Rows
ListBox1.Items.Add(String.Format("{0} {1} {2}", rad("id"), rad("fornavn"), rad("etternavn")))
Next rad
Is there anything I'm missing?
I am almost completed creating a VB.Net application, it currently works fine on a single run basis, the program loads in records of data from a localhost server, and will add and remove data fine. But i would like to have the ID of the latest entered record saved so that when the program is closed for however long, program can be reopened, and pulls the latest ID number to increment by one before being inputted into the database.
I am inputting my "latest" ID number into its own seperate table than the main "Stock Data" table.
How do i load my "latest" ID number into a temporary variable in my app that i can..
extract old ID
increment ID by one
input new record with incremented ID
replace old ID with new ID in database
code for reference...
Mysqlconn = New MySqlConnection
Mysqlconn.ConnectionString="server=localhost;userid=root;password=P#ssw0rd;database=stocklist"
Dim READER As MySqlDataReader
Query = "use stocklist;select IDsave from saves;"
COMMAND = New MySqlCommand(Query, Mysqlconn)
READER = COMMAND.ExecuteReader
Thank you in advance
Jay
Does your query result is always a single row?
If yes, then you have to use ExecuteScalar Function to get your data executed.
Mysqlconn = New MySqlConnection
Mysqlconn.ConnectionString="server=localhost;userid=root;password=P#ssw0rd;database=stocklist"
Dim READER As MySqlDataReader
Query = "use stocklist;select IDsave from saves;"
COMMAND = New MySqlCommand(Query, Mysqlconn)
READER = Convert.ToString(COMMAND.ExecuteScalar())
If your READER variable is not string, please convert query result to corresponding one.
I want a program that lets the user create his/her own query to retrieve data from the database. What is the best method to achieve such task? Any links or sample code would be much appreciated. Thank you.
I would go for :
Create a form, name it formSample
add a textbox, name it txbSample
add a datagridview, name it dgvSample
add a button, name it btnSample
txbSample will be used by the client to input queries
btnSample is where you would put the code.
dgvSample is the data, not really recommended but it's just used to show the data you have retrieved.
assuming you have connected to the database, the code on btnSample should look like
NOTE: not a complete code
Dim sql As String
sql = txbSample.text
Using cmd As New MySqlCommand
Try
'open the connection here
cmd.Connection = con
cmd.CommandText = sql
Dim dt As New DataTable
da = New MySqlDataAdapter(cmd)
da.Fill(dt)
'close the connection here
dgvSample.DataSource = dt
Catch ex As Exception
MessageBox.Show("Error while fetching data.")
'close the connection here
End Try
End Using
dt is a datatable where the data are stored. You should do something to be able to use it:)
Ladies & Gentlemen,
I have been, thus far, successful in programmatically pulling records from a MySQL database to create a crystal report from a single table. Using the code below, I'm trying to join two tables and display their matched records on the report:
Try
Dim myConnectionString As String = "Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=parts;Password=parts;Database=accounting;"
Dim dbConn As New MySqlConnection(myConnectionString)
Dim dbQuery As String = "SELECT * " & _
"FROM cc_master a JOIN customer b ON b.accountNumber = a.customer_accountNumber;"
Dim dbAdapter As New MySqlDataAdapter(dbQuery, dbConn)
Dim dbTable As New DataTable
dbAdapter.Fill(dbTable)
Dim report As New rptCardListAll
report.SetDataSource(dbTable)
CrystalReportViewer1.ReportSource = report
CrystalReportViewer1.Zoom(1)
Catch ex As Exception
'MsgBox(ex.Message)
End Try
The problem I'm running into now is that when the report runs at run-time, all the db records are populated on the report except for the one field that I'm pulling from the CUSTOMER table. Below is a screen shot. Notice the blank CUSTOMER NAME - this shouldn't be blank because I know for a fact there's data in that field for every record.
The query works fine when I run it directly on the DB using MySQL Workbench, so I can't figure out why the report won't pull the requested information. Any help would be appreciated, thanks.
EDIT: Screenshot showing DataSet Visualizer during debug containing the missing field (nameCOMPANY)
Good evening all,
So after hours of reading and searching the web, I've managed to arrive at or better yet, discover, a solution to my problem.
It appears that even though I'd created a DataSet within VS and used that to create my CR Report, I wasn't actually using that DataSet in code. Instead what I was doing was creating a new DataTable at run-time, filling that with my query result, and setting the report's datasource property to it.
What I should have been doing was to create an instance of my DataSet (the one I created earlier and used to design the report), fill it with my query result, and set the report's datasource property to it. This allowed CR to recognize and respect the table links/relationships I established earlier in the DataSet designer. I also learned that when using the DataAdapter with a query that returns multiple tables, the default naming convention is "Table" then "Table1" and so forth - that it was necessary to map these to the actual names of my tables in the DB.
So after applying all these lessons, I had to re-do my code as follows:
Dim report As New rptCardListAll
Dim myConnectionString As String = "Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=parts;Password=parts;Database=accounting;"
Dim dbConn As New MySqlConnection(myConnectionString)
Dim dbQuery As String = "SELECT * FROM cc_master; " & _
"SELECT * FROM customer;"
Dim dbAdapter As New MySqlDataAdapter(dbQuery, dbConn)
With dbAdapter
.TableMappings.Add("Table", "cc_master")
.TableMappings.Add("Table1", "customer")
End With
Try
Dim dbDataSet As New accountingDataSet
dbAdapter.Fill(dbDataSet)
report.SetDataSource(dbDataSet)
CrystalReportViewer1.ReportSource = report
CrystalReportViewer1.Zoom(1)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.OkOnly, "An Error Has Occured....")
End Try
My report now shows the missing field "nameCOMPANY" from the customer table.
CREDIT:
I want to thank #halfer, #luchosrock, and #EvilBob22 for their assistance. Also, I give credit to the authors in the following documents:
http://developer-content.emc.com/developer/downloads/CrystalReport_ADO_Dataset.pdf
How to fill Dataset with multiple tables?