I'm trying to create a project app, in said app i have a database to store data that the user inserts which i later use for various things.
I'm trying to get the value for the Weight and Height from the DB and im currently using this code:
Sub load()
Dim weight As Double
Using getData = New OleDbCommand("SELECT TOP 1 Weight FROM Data WHERE ID_User = #ID_User ORDER BY id DESC", conn)
getData.Parameters.Add("ID_User", OleDbType.VarChar).Value = My.Settings.currentUserID
If conn.State = ConnectionState.Closed Then conn.Open()
weight = getData.ExecuteScalar
End Using
Dim height As Integer
Using getData = New OleDbCommand("SELECT TOP 1 Height FROM Data WHERE ID_User = #ID_User ORDER BY id DESC", conn)
getData.Parameters.Add("ID_User", OleDbType.VarChar).Value = My.Settings.currentUserID
If conn.State = ConnectionState.Closed Then conn.Open()
height = getData.ExecuteScalar
End Using
End Sub
This works fine but im trying to reduce my code, is there a way to select multiple fields values in a single select query?
Example:
SELECT TOP 1 Weight, Height FROM Data WHERE ID_User = #ID_User ORDER BY id DESC
I already tried to use the example code but its just returning me the weight value twice for some unknown reason.
Thanks to #Jeremy and #ParrishHusband for helping me i managed to solve the problem, if anyone needs the solution this is how i did it:
Sub load()
Dim weight As Double
Dim height As Integer
Using getData = New OleDbCommand("SELECT TOP 1 Weight, Height FROM Data WHERE ID_User = #ID_User ORDER BY id DESC", conn)
getData.Parameters.Add("ID_User", OleDbType.VarChar).Value = My.Settings.currentUserID
If conn.State = ConnectionState.Closed Then conn.Open()
Dim reader As OleDbDataReader = getData.ExecuteReader
If reader.HasRows Then
While reader.Read
weight = reader.GetString(0)
height = reader.GetString(1)
End While
Else
MsgBox("No rows found")
End If
reader.Close()
End Using
MsgBox(weight & ", " & height)
End Sub
Related
I have a DataGridView and I'm adding a new row. But, when I add the new row it deletes the current row and replaces it.
This is the code
Try
con = New SqlConnection(cs)
con.Open()
cmd = New SqlCommand("SELECT ItemID, RTRIM(DishName),'1',Rate from Dish where ItemID like '" & TextBox1.Text & "' order by DishName", con)
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGridView1.Rows.Clear()
While (rdr.Read() = True)
DataGridView1.Rows.Add(rdr(0), rdr(1), rdr(2), rdr(3))
Dim num1 As Double
num1 = Val(DataGridView1.Rows(0).Cells("Qty").Value) * Val(DataGridView1.Rows(0).Cells("Rate").Value)
num1 = Math.Round(num1, 2)
DataGridView1.Rows(0).Cells("Amount").Value = num1
End While
TotalCalc()
Compute()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
I am having a little problem following your question
Suggestion Don't tell us you want a quick solution
If you are changing the value in the DB use Update
Here is some code to add values to a DataGridView with SQLite
The SELECT statement is a little odd due to another issue in my Project
Just use your SELECT also Welcome to Stackoverflow
Private Sub ViewSearches()
Dim intID As Integer
Dim strCodeDesc As String
Dim strUIProject As String
Dim strCodeType As String
Dim rowCount As Integer
Dim maxRowCount As Integer
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand("", conn)
If gvTxType = "View" Then
cmd.CommandText = "SELECT * FROM CodeTable WHERE cvCodeType = #site"
cmd.Parameters.Add("#site", DbType.String).Value = gvSCT
ElseIf gvTxType = "All" Then
cmd.CommandText = "SELECT * FROM CodeTable"
End If
Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
While rdr.Read()
intID = CInt((rdr("CID")))
strCodeDesc = rdr("cvCodeDesc").ToString
strUIProject = rdr("cvUIProject").ToString
strCodeType = rdr("cvCodeType").ToString
dgvSelCode.Rows.Add(intID, strCodeDesc, strUIProject, strCodeType)
rowCount += 1
End While
dgvSelCode.Sort(dgvSelCode.Columns(3), ListSortDirection.Ascending)
End Using
If rowCount <= 12 Then
maxRowCount = 12 - rowCount
For iA = 1 To maxRowCount
dgvSelCode.Rows.Add(" ")
Next
End If
End Using
End Using
End Sub
Desired chart
Current chart
Hey guys, Im trying to make a column chart using the purok and status column. How can you show the PWD and Pregnant as a bar with label and count also? thankyou in advance
The table name is PWDPregnant | columnName "status" is for PWD/Pregnant. | columnName "purok" is for Pepsi/Coke.
Dim dt As New DataTable
Using pwdcon As New OleDbConnection(con.ConnectionString),
cmd As New OleDbCommand("SELECT purok, status, COUNT(*) As RecCount FROM PWDPregnant GROUP BY purok, status ORDER BY purok", con)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Chart5.Series("PWD").XValueMember = "purok"
Chart5.Series("PWD").YValueMembers = "status"
Chart5.Series("PWD").Label = "#AXISLABEL #VALY"
Chart5.Series("Pregnant").YValueMembers = "status"
Chart5.Series("Pregnant").Label = "#AXISLABEL #VALY"
Chart5.DataSource = dt.DefaultView
Chart5.DataBind()
Finally I found the fix but it still cant support the 2nd series which is Pregnant.
Dim dt As New DataTable
Using pwdcon As New OleDbConnection(con.ConnectionString),
cmd As New OleDbCommand("SELECT purok, status, COUNT (*) as RecCount FROM PWDPregnant WHERE status = #stat GROUP BY purok, status", con)
cmd.Parameters.Add("#stat", OleDb.OleDbType.VarChar).Value = "PWD"
If con.State = ConnectionState.Closed Then
con.Open()
End If
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Chart5.ChartAreas(0).AxisX.Interval = 1
Chart5.Series("PWD").XValueMember = "purok"
Chart5.Series("PWD").YValueMembers = "RecCount"
Chart5.Series("PWD").Label = "#VALY"
Chart5.DataSource = dt.DefaultView
Chart5.DataBind()
how to display result from data base into textbox and if the result exceed 1 key up and down to preview
con = New SqlConnection(cs)
con.Open()
Dim sql As String = " Select RTRIM(visit.regdate),RTRIM(Patientno) from visit where visit.accno =#d6 "
cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("d6", accno.Text)
rdr = cmd.ExecuteReader()
While (rdr.Read() = True)
regdate.Value = rdr.GetValue(0)
patientno.Text = rdr.GetValue(1)
End While
You must use listbox instead textbox to put your data, here is an example:
ListBox1.ColumnCount = 3
ListBox1.Columnwidths = "100,100,100"
ListBox1.AddListItem("row1 col1", 1,1)
ListBox1.AddListItem("row1 col2", 1,2)
ListBox1.AddListItem("row2 col2", 2,2)
I have a button and once clicked you are required to enter the customersID and once entered the data from that whole row should then load into the text box's, checkbox etc but when i do it, it prompts me with my own error i created saying Customer not found because it cant locate the ID of some sort? Any help appreciated!
In my opinion - When it loads * (All) from where ID is i am thinking it is only loading in all that data from that specific row at that Customer ID (in which i want) so i could use rows.items etc to load in my required information? Is this correct or? In general i just need help retrieving the data and putting it into my text boxes and such.
Code:
Private Sub Client(ByVal ans As String)
If con.State = ConnectionState.Closed Then con.Open()
cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "Select * FROM tbl WHERE ID = ?"
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ans
If cmd.ExecuteNonQuery() = 0 Then
MsgBox("Does not exist!", MsgBoxStyle.Critical, "Enter new ID!")
Else
MessageBox.Show("Now loaded.", "Search Complete!", MessageBoxButtons.OK, MessageBoxIcon.Information)
If con.State = ConnectionState.Closed Then con.Open()
'create data adapters
sql = "Select * from tbl"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "tbl")
RecCnt = ds.Tables("tbl").Rows.Count 'how many records in ds
'assign data to lables
TxtCI.Text = ds.Tables("tbl").Rows(0).Item(0)
con.Close()
End If
cmd.ExecuteNonQuery()
con.Close()
End Sub
Caller (Search button):
Client(custid)
ExecuteNonQuery cannot work correctly with a SELECT statement. The returned value is the number of the rows affected but a SELECT statement doesn't change, insert or delete any row, so it is always zero.
You should use ExecuteReader (and this removes also the need to use an OleDbDataAdapter, a DataTable/Dataset and the long winded statement lines to retrieve values from the DataSet/Tables/Rows/Columns hierarchy
If con.State = ConnectionState.Closed Then con.Open()
cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "Select * FROM tblcustomer WHERE CustomerID = ?"
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ans
Dim reader As OleDbDataReader = cmd.ExecuteReader()
if reader.Read() Then
TxtCI.Text = reader(0).ToString()
TxtName.Text = reader(1).ToString()
... and so on ...
Else
MsgBox("Customer Does not exist!", ....)
Notice that you could substitute the column index (0,1,2 etc...) with the column name ("CI", "Name" etc...). This is somewhat better because it doesn't depend on the order returned by the SELECT * query (Of course, if you change the columns names you have the same problem but, at least, you should know about the change)
How to find the largest value in a column of a access table. and displayed in a text box. I give 101 as the default value of the column and the table is empty. I try like this.. But its not working. Code is given below
Dim empid As Integer
empid=101
TXTEMPID.Text=empid
getConnect()
Dim strSQL As String = "SELECT MAX(EMP_ID) FROM EMPLOYEE "
Dim cmd As OleDb.OleDbCommand
Dim Reader As OleDb.OleDbDataReader
cmd = New OleDb.OleDbCommand(strSQL, Conn)
Try
Conn.Open()
Reader = cmd.ExecuteReader()
If Reader.Read Then
empid = CInt(Reader("EMP_ID"))
End If
MessageBox.Show(empid)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Conn.Close()
End Try
TXTEMPID.Text = empid + 1
If the table is empty then there is no "largest value" because the table contains no values at all.
Edit
Ah, okay. It sounds like you were tripping over the fact that, for an empty table, expressions like DMax("EMP_ID","YourTable") will return Null, and Null + 1 will return Null, so how do we get started? You could try something like...
Me.txtEMP_ID.Value = Nz(DMax("EMP_ID","YourTable"), 100) + 1
...in the Form Load event, although I should mention that this type of approach can cause problems is your database is (or will ever become) multi-user.
here is the query
Select Top 1 MAX(col 2), col1 from Table1 group by col1
to get the results you have to perform
Dim cnnOLEDB As New OleDbConnection
Dim cmdOLEDB As New OleDbCommand
Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.Environment.CurrentDirectory & "\URDataBaseName.mdb"
cnnOLEDB.ConnectionString = strConnectionString
cnnOLEDB.Open()
cmdOLEDB.CommandText ="Select Top 1 MAX(col 2), col1 from Table1 group by col1"
cmdOLEDB.Connection = cnnOLEDB
txtbox.text = cmdOLEDB.ExecuteScalar().ToString()
ExecuteScalar Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored
I change my code like this given below.. Its working coooool......
getConnect()
Conn.Open()
Dim str As String
Dim newNumber As Integer
str = "SELECT MAX(EMP_ID) AS MAXIMUM FROM EMPLOYEE"
Dim cmd As OleDbCommand = New OleDbCommand(str, Conn)
Dim dr As OleDbDataReader
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
TXTEMPID.Text = dr("MAXIMUM").ToString
newNumber = CInt(Val(TXTEMPID.Text))
If newNumber = 0 Then
newNumber = 101
TXTEMPID.Text = CStr(newNumber)
Else
newNumber = newNumber + 1
TXTEMPID.Text = CStr(newNumber)
End If
End While
End If
Conn.Close()
Thank you all for replay and comment my question