Select max value in MS Access database - vb.net

I need to select the max value in my row column. When I hit line
(FindCurrentTimeCard = Val(myreader("Row"))
I get an error:
System.IndexOutOfRangeException
Code:
Public Function FindCurrentTimeCard() As Integer
Dim myconnection As OleDbConnection = New OleDbConnection
Dim query As String = "Select MAX(Row) from Table2"
Dim dbsource As String =("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=S:\Docs\PRODUCTION\Shop Manager\Shop_Manager\Shop_Manager\Database2.accdb;")
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
Try
conn.Open()
Dim myreader As OleDbDataReader = cmd.ExecuteReader()
myreader.Read()
FindCurrentTimeCard = Val(myreader("Row"))
conn.Close()
Catch ex As OleDbException
MessageBox.Show("Error Pull Data from Table2")
FindCurrentTimeCard = 1
End Try
End Function
Table2

The issue is that when you evaluate an aggregate function (or indeed, any expression performing some operation on a field or fields), the result of such evaluation will be assigned an alias (such as Expr1000) unless an alias is otherwise stated.
Hence, when you evaluate the SQL statement:
select max(table2.row) from table2
MS Access will return the result assigned to an alias such as Expr1000:
Hence, the SQL statement does not output a column named Row, causing your code to fail when attempting to retrieve the value of such column:
FindCurrentTimeCard = Val(myreader("Row"))
Instead, you should specify an alias to which you may refer in your code, e.g.:
select max(table2.row) as maxofrow from table2
With your function then returning the value associated with such column:
FindCurrentTimeCard = Val(myreader("maxofrow"))

Comments and explanations in-line
Public Function FindCurrentTimeCard() As Integer
Dim CurrentTimeCard As Integer
'The Using block ensures that your database objects are closed and disposed
'even it there is an error
'Pass the connection string directly to the connection constructor
Using myconnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=S:\Docs\PRODUCTION\Shop Manager\Shop_Manager\Shop_Manager\Database2.accdb;")
Dim query As String = "Select MAX(Row) from Table2"
Using cmd As New OleDbCommand(query, myconnection)
Try
myconnection.Open()
'since you are only retrieving a single value
'you can used .ExecuteScalar which gets the value
'in the first row, first column
CurrentTimeCard = CInt(cmd.ExecuteScalar)
Catch ex As OleDbException
MessageBox.Show("Error Pull Data from Table2")
End Try
End Using
End Using
'vb.net uses the Return statement to return the value of the function
Return CurrentTimeCard
End Function

Related

Insert Into Syntax error vb.net

Good Day
I am using VB 2017 to create an application. i am using an Access Database.
When i an running my code i get an Insert Into Syntax error
my code is as follows.
Please help.
Public Shared Function AddLocation(location As Location) As Integer
Dim connection As OleDbConnection = AutoBeautyCareDB.GetConnection
Dim insertStatement As String = "Insert Into Location (CUST#,HOSP_ID,FLOOR,ROOM) VALUES(?,?,?,?)"
Dim insertCommand As OleDbCommand = New OleDbCommand(insertStatement, connection)
insertCommand.Parameters.AddWithValue("Cust#", location.CustNo.ToString)
insertCommand.Parameters.AddWithValue("HospId", location.HospId.ToString)
insertCommand.Parameters.AddWithValue("Floor", location.Floor.ToString)
insertCommand.Parameters.AddWithValue("Room", location.Room.ToString)
Try
connection.Open()
insertCommand.ExecuteNonQuery()
Dim selectStatement As String = "Select ##Identity"
Dim selectCommand As New OleDbCommand(selectStatement, connection)
insertCommand.CommandText = selectStatement
Dim locationId As Integer = insertCommand.ExecuteScalar
Return locationId
Catch ex As OleDbException
Throw ex
Finally
connection.Close()
End Try
End Function
When you use a special symbol like # you need to enclose the field name between square brackets, however it is best to change that name to something less problematic
Dim insertStatement As String = "Insert Into Location
([CUST#],HOSP_ID,FLOOR,ROOM)
VALUES(?,?,?,?)"
Also remember that AddWithValue, while it seems to be a useful shortcut, has many problems as explained in the following article
Can we stop using AddWithValue already?
A single line approach with better parameter handling is the following
insertCommand.Parameters.Add("Cust#", OleDbType.Integer).Value = location.CustNo
(Assuming Cust# is an integer type in your database table)

Check if a table is empty on SQLite

I'm trying to adapt to VB.NET the code of the most voted answer from this post:
Sqlite Check if Table is Empty
Original code is
SQLiteDatabase db = table.getWritableDatabase();
String count = "SELECT count(*) FROM table";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
//leave
else
//populate table
My code looks like ('Only to have a message on the screen I will fill the If - Else code later')
Using conn As New SQLiteConnection("Data Source=myDataBase.sqlite;Version=3;foreign keys=true")
Try
conn.Open()
Dim emptyUserTable = "SELECT COUNT(*) FROM usersTable"
Dim cmdIsEmpty As SQLiteCommand = New SQLiteCommand(emptyUserTable, conn)
Try
Dim Answer As Integer
Answer = cmdIsEmpty.ExecuteNonQuery()
MsgBox(Answer)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Using
But the "Answer" is allways -1, with empty table or not.
I donĀ“t know how to use getWritableDataBase because I get a
getWritableDatabase is not a member of SQLiteConnection
The same with rawQuery.
How can I check if usersTable is empty or not on VB.NET?
I've abstracted your code a little so it can be used for any table:
Private Function IsTableEmpty(tblName As String) As Boolean
Dim sql = String.Format("SELECT COUNT(*) FROM {0}", tblName)
Using conn As New SQLiteConnection(LiteConnStr)
Using cmd As New SQLiteCommand(sql, conn)
conn.Open()
Dim rows = Convert.ToInt32(cmd.ExecuteScalar())
Return rows = 0
End Using
End Using
End Function
Usage:
If IsTableEmpty("usersTable") Then
Console.Beep()
End If
Notes
The command object should be disposed when you are done with it, so it is used on a Using block.
There is not need to copy your connection string everywhere. You can define it once as a form/class level variable and reuse it everywhere
ExecuteScalar() gets the count back, then it is tested for 0 rows

SQL injection method for select statement

I want to get same values form my database therefore I'm using this query:
SELECT NormalComputers
FROM usb_compliance
WHERE ATC = 'CMB'
ORDER BY date DESC
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
Using this I want to get so many values so I plan to use SQL injection method please help me how to create this
If I can use injection method I can use function it should be like this
Private Function query(ByVal values As String, ByVal atc As String, ByVal no As Integer)
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
connetionString = "Server=CTV-WEBDEVEXG;Database=usb;Trusted_Connection=True;"
sql = "SELECT #values FROM usb_compliance WHERE ATC=#atc ORDER BY date DESC OFFSET #no ROWS FETCH NEXT 1 ROWS ONLY"
connection = New SqlConnection(connetionString)
Try
command = New SqlCommand(sql, connection)
With command
.Connection.Open()
MsgBox("done !!!")
.CommandType = CommandType.Text
.Parameters.Add("#values", SqlDbType.DateTime).Value = values
.Parameters.Add("#atc", SqlDbType.NVarChar).Value = atc
.Parameters.Add("#NormalComputers", SqlDbType.Int).Value = no
End With
command.ExecuteNonQuery()
command.Dispose()
connection.Close()
Catch ex As Exception
End Try
Return sql
End Function
I have tried this way but its not working so please help me on this
parameter #values refers to the name of the field you want to retrieve. So it owes to be a string not a DateTime (despite the fact that this filed datatype might be DateTime).
...
.Parameters.Add("#values", SqlDbType.NVarChar).Value = values
...
to get rows affected:
Dim numRows as Integer
...
..
numRows=command.ExecuteNonQuery()

How to count number of rows in a sql table with vb.net using sqlclient class

SELECT count(*) FROM table name
this above code work fine in standalone sql table, but who can I do this simple task with in vb.net wpf project ?
This is only a sample ..just check and try your own way.
Sample:
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;
User ID=UserName;Password=Password"
sql = "Select count(*) from table"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
MsgBox("Count =" & sqlReader.Item(0))
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
If your query return more than one values you can use SqlDataReader(), but if you are sure your query will return only a single value you can use ExecuteScalar() and if your query wont return any result, eg:- insert.it will insert value not return any data so we can use ExecuteNonQuery().The ExecuteNonQuery() will return a result which indicate is it successful or failure. If you want you can assign the same else no need.
Use SqlCommand.ExecuteScalar() method to execute query that return singular/scalar value (example based on that link) :
Dim count As Integer
Dim connString = "connection string to your database here"
Using conn As New SqlConnection(connString)
Dim cmd As New SqlCommand("SELECT COUNT(*) FROM MyTable", conn)
Try
conn.Open()
count = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using

How to handle DBNull? VB.NET

I have form that has datagrid and some textbox controls.
Basically, Im performing Add function. Whenever I add, it scans the maximum value and it will increment by one. I only designed for auto increment. My problem is, how can I increment when the ExecuteScalar gets a null value.
Here's the sample codes
Public Sub IncrementID()
conn = New MySqlConnection
conn.ConnectionString = "server=localhost; userid=root; password=root; database=uecp_cens"
Try
conn.Open()
Dim insert_coupon_query As String = ("SELECT MAX(faculty_ID) from uecp_cens.tblfacultyinfo")
Dim cmd_query As New MySqlCommand(insert_coupon_query, conn)
Dim cmd_result As Integer = CInt(cmd_query.ExecuteScalar()) 'THIS IS WHERE THE ERROR OCCURS, IT GIVES ME 'InvalidCastException was unhandled' Conversion from type 'DBNull' to type 'Integer' is not valid.
txtFacultyNo.Text = cmd_result + 1
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
Any help is appreciated.
Reference For More Help , Click Here
you should write this casting
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();