I have the following code. Please help me on how to get the last record of the records.
Dim DteQry As New OdbcCommand
DteQry.CommandText = "select distinct trn_date from order_data order by trn_date asc limit 30;"
Conn.open()
DteQry.Connection = Conn
Dim qryRdr As OdbcDataReader
qryRdr = DteQry.ExecuteReader()
If qryRdr.HasRows() Then
Dim StartDte = qryRdr.GetValue(0)
TextBox2.Text = qryRdr.GetValue(0)
Exit Sub
End If
How about this...
You cannot get the row count directly from OdbcDataReader. So just create the dataTable dt and load the dataset from reader to dt. Get the row count from datatable and then you can get last record as below.
If qryRdr.HasRows() Then
Dim dt As DataTable
dt.Load(qryRdr)
Dim StartDte = dt.Rows(dt.Rows.Count-1).item(0)
TextBox2.Text = dt.Rows(dt.Rows.Count-1).item(0)
Exit Sub
End If
dim Last_record as integer
Dim tb As DataTable
dim dp = New OleDbDataAdapter("select max(ID) from tb2", cn)
dp.Fill(tb)
If Not IsDBNull(tb.Rows(0).Item(0)) Then Last_record = tb.Rows(0).Item(0)
tb.clear
SELECT * FROM TableName WHERE id=(SELECT max(id) FROM TableName);
Related
Hello i am trying to search for data from a table using a funcion, however when i Input the number of the customerID it doesnt show up in the data gridview but the data is still passed to my textboxes. Could anyone help me in explaining what I did wrong?
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim newds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = Fname
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "customers")
dt = newds.Tables(0)
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
dgvCustomerInfo.DataSource = dt
con.Close()
End Using
Return dt
End Function
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
If txtSearchName.Text <> "" Then
SearchData(txtSearchName.Text, "0")
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
ElseIf txtSearchID.Text <> "" Then
SearchData("0", txtSearchID.Text)
Dim dt = GetSearchResults(txtSearchID.Text)
dgvCustomerInfo.DataSource = dt
End If
End Sub
Try to think about what each line of code is doing. See in line comments
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
'Delete this line - there is no need for a Dataset
Dim newds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open() 'Move this line - don't open the connection until directly before the .Execute...
'The Like operator would expect a pattern to match
'The interpolated string with the percent signs add wildcard characters
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
'Delete - We don't need a DataAdapter
Dim da As New SQLiteDataAdapter(cmd)
'Delete - We already have a filled DataTable
da.Fill(newds, "customers")
'Delete - same as above
dt = newds.Tables(0)
'Delete - Have no idea what this does. You are already going to display your data in a grid
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
'Delete - You will set the DataSource in the User Interface code
dgvCustomerInfo.DataSource = dt
'Delete - End Using closes the connection and disposes the connection and command.
con.Close()
End Using
Return dt
End Function
The corrected code will look like this.
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
In the user interface code I have added in line comments.
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
'Declare the DataTable outside the If block
'We do not need a New DataTable because SearchData is returning a DataTable
Dim dt As DataTable
If txtSearchName.Text <> "" Then
'Call only one function to return the DataTable
'SearchData is expecting 2 parameters, a String and an Integer
'Putting 0 in quotes makes it a String
dt = SearchData(txtSearchName.Text, 0)
'I removed the DataSource, Don't repeat yourself
'Assign it once after the If
ElseIf txtSearchID.Text <> "" Then
'The second argument must be an Integer, therefore the CInt()
dt = SearchData("", CInt(txtSearchID.Text))
Else
'Needed to add an Else to assign a value to dt if all else fails
dt = Nothing
End If
dgvCustomerInfo.DataSource = dt
End Sub
database name is 'randomTable'
first col name is 'id'
2nd col name is 'name'
How do I get the value of 'name' col, same way I am getting the rows count?
Protected Sub BindGridData()
' Connect to databse and open database file
Dim da As SqlDataAdapter
Dim ds As DataSet = New DataSet()
Dim query As String = "SELECT * FROM [randomTable]"
Dim sqlConn As New SqlConnection(myCon)
Try
sqlConn.Open()
Dim cmd = New SqlCommand(query, myCon)
da = New SqlDataAdapter(cmd)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(da)
da.Fill(ds, "randomTable")
Dim a As Integer = ds.Tables("randomTable").Rows.Count
If a = 0 Then
e.Text = "empty"
End If
'this line is wrong - ???
Dim s As String = ds.Tables("randomTable").Columns("name")
if s = "value1"
'do something
end if
GridView1.DataSource = ds.Tables("randomTable").DefaultView
GridView1.DataBind()
sqlConn.Close()
Catch ex As Exception
End Try
End Sub
If you want the rows Count, you can execute a query tu Database "SElect Count() from randomTable". But in specific what do you want to do?
Either index by a specific row or iterate the row collection e.g.
Dim s As String = ds.Tables("randomTable").Rows(0).Field(Of String)("name")
If s = "value1" Then
'do something
End If
' or
For row As Integer = 0 To ds.Tables("randomTable").Rows.Count
If ds.Tables("randomTable").Rows(row).Field(Of String)("name") = "value1" Then
' do something
End If
Next
I have a DataTable that is built like this:
Dim dt As New DataTable()
dt = SqlHelper.ExecuteDataset(connString, "storedProcedure", Session("Member"), DBNull.Value, DBNull.Value).Tables(0)
Then it is converted to a DataView and exported to Excel like this:
Dim dv As New DataView()
dv = dt.DefaultView
Export.CreateExcelFile(dv, strFileName)
I want to add another column and fill it with data before I export to Excel. Here's what I'm doing now to add the column:
Dim dc As New DataColumn("New Column", Type.GetType("System.String"))
dc.DefaultValue = "N"
dt.Columns.Add(dc)
Then to populate it:
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(dt.Columns(0).ColumnName)
Dim pID As String = dt.Columns(0).ColumnName
Dim qry As String = "SELECT * FROM [MyTable] WHERE [UserID] = " & uID & " AND [PassID] = '" & pID & "'"
Dim myCommand As SqlCommand
Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
myConn.Open()
myCommand = New SqlCommand(qry, myConn)
Dim reader As SqlDataReader = myCommand.ExecuteReader()
If reader.Read() Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
Next row
But I get a "System.FormatException: Input string was not in a correct format." error when I run the app. It doesn't seem to like these lines:
Dim uID As Integer = Convert.ToInt32(dt.Columns(0).ColumnName)
Dim pID As String = dt.Columns(0).ColumnName
I think I have more than one issue here because even if I comment out the loop that fills the data in, the column I created doesn't show up in the Excel file. Any help would be much appreciated. Thanks!
EDIT:
Okay, I was grabbing the column name instead of the actual data in the column... because I'm an idiot. The new column still doesn't show up in the exported Excel file. Here's the updated code:
Dim dt As New DataTable()
dt = SqlHelper.ExecuteDataset(connString, "storedProcedure", Session("Member"), DBNull.Value, DBNull.Value).Tables(0)
Dim dc As New DataColumn("New Column", Type.GetType("System.String"))
dc.DefaultValue = "N"
dt.Columns.Add(dc)
'set the values of the new column based on info pulled from db
Dim myCommand As SqlCommand
Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
Dim reader As SqlDataReader
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(row.Item(0))
Dim pID As String = row.Item(2).ToString
Dim qry As String = "SELECT * FROM [MyTable] WHERE [UserID] = " & uID & " AND [PassID] = '" & pID & "'"
myConn.Open()
myCommand = New SqlCommand(qry, myConn)
reader = myCommand.ExecuteReader()
If reader.Read() Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
myConn.Close()
Next row
dt.AcceptChanges()
Dim dv As New DataView()
dv = dt.DefaultView
Export.CreateExcelFile(dv, strFileName)
I suppose that you want to search your MyTable if it contains a record with the uid and the pid for every row present in your dt table.
If this is your intent then your could write something like this
Dim qry As String = "SELECT UserID FROM [MyTable] WHERE [UserID] = #uid AND [PassID] = #pid"
Using myConn = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
Using myCommand = new SqlCommand(qry, myConn)
myConn.Open()
myCommand.Parameters.Add("#uid", OleDbType.Integer)
myCommand.Parameters.Add("#pid", OleDbType.VarWChar)
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(row(0))
Dim pID As String = row(1).ToString()
cmd.Parameters("#uid").Value = uID
cmd.Parameters("#pid").Value = pID
Dim result = myCommand.ExecuteScalar()
If result IsNot Nothing Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
Next
End Using
End Using
Of course the exporting to Excel of the DataTable changed with the new column should be done AFTER the add of the column and this code that updates it
In this code the opening of the connection and the creation of the command is done before entering the loop over your rows. The parameterized query holds the new values extracted from your ROWS not from your column names and instead of a more expensive ExecuteReader, just use an ExecuteScalar. If the record is found the ExecuteScalar just returns the UserID instead of a full reader.
The issue was in my CreateExcelFile() method. I inherited the app I'm modifying and assumed the method dynamically read the data in the DataTable and built the spreadsheet. In reality, it was searching the DataTable for specific values and ignored everything else.
2 lines of code later, I'm done.
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
Through ADO,I like to do the following query:
select name, address, zip from terr where id = '33334'
I like then to assign name, addess, zip to variables so that I can assign it later in my program.
How do I do this with VB.NET ADO?
Try somethign like this:
Dim dbName As String
Dim dbAddress As String
Dim dbZip As String
Using connObj As New SqlClient.SqlConnection("<connectionString>")
Using cmdObj As New SqlClient.SqlCommand("select name, address, zip from terr where id = '33334'", connObj)
connObj.Open()
Using readerObj As SqlClient.SqlDataReader = cmdObj.ExecuteReader
'This will loop through all returned records
While readerObj.Read
dbName = readerObj("name").ToString
dbAddress = readerObj("address").ToString
dbZip = readerObj("zip").ToString
'handle returned value before next loop here
End While
End Using
connObj.Close()
End Using
End Using
Also, you should look into parameterizing the value for the where clause.
You need a DataBase (i assume MS Sql-Server), a Connection and a DataAdapter to fill a DataTable. Then you have all you need. Here's an example:
Public Function GetUser(UserId As Int32) As DataRow
Using con = New SqlConnection(My.Settings.RM2ConnectionString)
Using cmd = New SqlCommand("select name, address, zip from terr where id = #id", con)
cmd.Parameters.AddWithValue("#id", UserId)
Dim da = New SqlDataAdapter(cmd)
Dim tblUser = New DataTable
da.Fill(tblUser)
If tblUser.Rows.Count <> 0 Then
Return tblUser(0)
Else
Return Nothing
End If
End Using
End Using
End Function
execute a SqlCommand from SQLDatareader, like:
Dim vVendedor As New SqlCommand("SELECT user FROM users", mConeccion)
vDatosVen = vVendedor.ExecuteReader
vVendedor = Nothing
and to get te value:
While vDatosVen.Read()
vUser = vDatosVen("user")
End While
Here's what i did...
Private Sub btn_Connect_Click(sender As Object, e As EventArgs) Handles btn_Connect.Click
Dim sql_connection As New MySqlConnection
Dim sql_query As New MySqlCommand
Dim sql_result As MySqlDataReader
sql_connection.ConnectionString = "Server=localhost;Database=hidden;Uid=root;Pwd=;"
sql_query.Connection = sql_connection
sql_connection.Open()
sql_query.CommandText = "SELECT Entry,name FROM table WHERE entry=1;"
sql_result = sql_query.ExecuteReader
If sql_result.HasRows Then
Do While sql_result.Read()
Dim query_result As String
query_result = sql_result("name")
MsgBox(query_result)
Loop
Else
MsgBox("No results found.")
End If