Programaticly Limiting number of rows for mysql database using VB.net - mysql

Good day I have written a function that needs to limit the number of employees that can be added to the database.
<WebMethod()>
Public Function EmployeeSubToken()
Dim cmd As New SqlCommand("Select vchSubscriptionType FROM BillingInfo", con)
Dim subtype = "vchSubscriptionType"
Dim Token
Select Case subtype
Case subtype = "Bronze"
Token = 1
Case subtype = "Silver"
Token = 2
Case subtype = "Gold"
Token = 3
Case subtype = "Platinum"
Token = 4
End Select
Dim cmd2
Select Case Token
Case Token = 1
cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 5")
Case Token = 2
cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 10")
Case Token = 3
cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 25")
Case Token = 4
cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment")
End Select
End Function
Does anyone know how If this is the correct way of doing it? if it is not how would I accomplish this?

if you want to limit the inserts, have a function that will query your database and return a count of rows, SELECT COUNT(*) FROM dtEmployment ; then just use a simple if,
if(dtEmploymentCount < MydesiredCount) then
'Do My Insert
else
'Return your message (Maximum amount of entries reached)
end If

maybe TOP(5) your looking for.
is there any order to the rows your returning, i.e. does it matter which 5 are returned?

Related

Query by date with ASP and MySQL

I need to make a query in a MySQL database returning records with the current date.
I found the command below and it works perfectly inside MySQL:
SELECT * FROM TBAvaliacoes WHERE DataHora = (Date_Format(Now(),'%Y-%m-%d'))
But when I do this inside ASP, it returns me the error below:
See how I am doing:
' ## LISTA RAMAIS
Set cmdListaAvaliacoes = Server.CreateObject("ADODB.Command")
cmdListaAvaliacoes.ActiveConnection = conn
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes WHERE DataHora = (Date_Format("&Now()&",'%Y-%m-%d'))"
response.write cmdListaAvaliacoes.CommandText
cmdListaAvaliacoes.CommandType = 1
Set rsListaAvaliacoes = Server.CreateObject("ADODB.Recordset")
rsListaAvaliacoes.Open cmdListaAvaliacoes, , 3, 3
If I enclose Now () in single quotation marks, it gives no error, but returns nothing.
Does anyone know how to get around this?
Awaiting,
If you want to call the Now() function defined by MySql then you shouldn't use the VB.NET function and concatenate its output to your sql. Just write the code exactly how you write it in the MySql Workbench
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = (Date_Format(Now(),'%Y-%m-%d'))"
If you want to pass a particular date then you need to format your date as expected by MySql
Dim myDate As DateTime = new DateTime(2019,8,10)
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = '" & myDate.ToString("yyyy-MM-dd") & "'"
But in this case the better approach is to use parameters (even if you have full control of what your date is)
Dim myDate As DateTime = new DateTime(2019,8,10)
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = #dat"
Dim prm = cmdListaAvaliacoes.CreateParameter("#dat", adDBDate, adParamInput)
prm.Value = myDate
cmdListaAvaliacoes.parameters.Append prm
Side note
A lot of time has passed from the last time I have used ADODB. So the parameter solution is how I remember it. Search on the net for more complete CreateParameter examples

How to check only month and year in MySQL DateTime column in Vb.net

Im saving some calculated values in to database each month.Before saving, i want to check data is already available for this month and year. IF the same month exists, then user has to select another month or leaving without saving that. In Vb.net, im using DateTimepicker for selecting month and save that in DateTIme format in mysql. In that i want to check only month and year is existing.
Mysql:
1 2019-05-01 14:24:20 ProA 8.34 3.59
2 2019-05-01 14:24:20 ProB 9.21 5.54
Here record available for ProA for May2019 is available. So user cannot save for may 2019 again.
Dim selectedDate = DateTimePicker1.Value
Dim startDate = New Date(selectedDate.Year, selectedDate.Month, 1)
conn.Open()
sQuery = "SELECT * FROM riskanalysis WHERE DATE_FORMAT(reportdate,'%c %Y') >= #StartDate "
cmd_listview = New MySqlCommand(sQuery, conn)
cmd_listview.Parameters.AddWithValue("#StartDate", startDate)
Using reader As MySqlDataReader = cmd_listview.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("Record Already Exist for this Month!", MsgBoxStyle.Exclamation, "Select another month!")
Else
sQuery = "INSERT INTO riskanalysis (reportdate, process, avgrisk, avgriskafterImp) VALUES (#dat, #process, #avgrisk, #riskafterimp);"
For i As Integer = 0 To ProcessRiskGridView.Rows.Count - 1
cmd_listview = New MySqlCommand(sQuery, conn)
cmd_listview.Parameters.AddWithValue("dat", DateTimePicker1.Value)
cmd_listview.Parameters.AddWithValue("process", ProcessRiskGridView.Rows(i).Cells(0).Value)
cmd_listview.Parameters.AddWithValue("avgrisk", ProcessRiskGridView.Rows(i).Cells(1).Value)
cmd_listview.Parameters.AddWithValue("riskafterimp", ProcessRiskGridView.Rows(i).Cells(2).Value)
cmd_listview.ExecuteNonQuery()
Next
End Using
conn.Close()
I tried for some mysql command but it didnt work.
You don't need to Select * to find out if a record exists. Just get the count. Don't retrieve data you don't need. You certainly don't need a reader.
Keep your database objects local so you can be sure they are closed and disposed. `Using...End Using blocks will handle this for you even if there is an error.
Don't use .AddWithValue See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
You keep adding parameters to the collection over and over on each iteration. They only need to be added once. The value of #dat remains the same for all iterations. Only the values of the last 3 parameters change. You seem to be mixing up column names and parameter names. We are dealing with parameter names.
I have guessed at datatypes. Check your database for the actual datatypes and be sure to convert the values from the grid cells to the proper type if necessary. I don't know what kind of grid you are using and if it returns proper datatypes for .Value.
Example:
cmd.Parameters("#avgrisk") = CDbl(ProcessRiskGridView.Rows(i).Cells(1).Value)
Private Sub MySql()
Dim retVal As Integer
Dim selectedDate = DateTimePicker1.Value
Dim startDate = New Date(selectedDate.Year, selectedDate.Month, 1)
Dim sQuery = "SELECT Count(*) FROM riskanalysis WHERE DateTimeColumnName >= #StartDate; "
Using conn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand(sQuery, conn)
cmd.Parameters.Add("#StartDate", MySqlDbType.DateTime).Value = startDate
conn.Open()
retVal = CInt(cmd.ExecuteScalar)
End Using
End Using
If retVal <> 0 Then
MessageBox.Show("Record Already Exist for this Month!")
Return
End If
sQuery = "INSERT INTO riskanalysis (reportdate, process, avgrisk, avgriskafterImp) VALUES (#dat, #process, #avgrisk, #riskafterimp);"
Using cn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand(sQuery, cn)
With cmd.Parameters
.Add("#dat", MySqlDbType.DateTime).Value = selectedDate
.Add("#process", MySqlDbType.VarChar)
.Add("#avgrisk", MySqlDbType.Double)
.Add("#riskafterimp", MySqlDbType.Double)
End With
cn.Open()
For i As Integer = 0 To ProcessRiskGridView.Rows.Count - 1
cmd.Parameters("#process").Value = ProcessRiskGridView.Rows(i).Cells(0).Value
cmd.Parameters("#avgrisk") = ProcessRiskGridView.Rows(i).Cells(1).Value
cmd.Parameters("#riskafterimp") = ProcessRiskGridView.Rows(i).Cells(2).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub

How to calculate the expiration date 3 months before will be expire

I need help how to get 3 months before expiration date alert. I used mysql.
Try
Call connection()
cmd.CommandText = "select * from medicine where expiry_date < date_sub(now(), interval 3 month)"
dr = cmd.ExecuteReader
count = 0
While dr.Read
count = count + 1
End While
If count = 1 Then
pop.Image = Image.FromFile("E:\asasda.png")
pop.TitleText = "Notification Alert!!!"
pop.ContentText = "Medicine at Risk"
pop.AnimationDuration = 3000
pop.Popup()
Else
pop.Image = Image.FromFile("E:\asasda.png")
pop.TitleText = "Notification Alert!!!"
pop.ContentText = "No items for risk"
pop.AnimationDuration = 3000
pop.Popup()
End If
Catch ex As Exception
End Try
I commented our Call Connection(). It is best to keep your connections local so you can be sure they are closed and disposed.
A Using...End Using block will accomplish this even it there is an error. Also I don't see where you associated a connection to your command. The call keyword is not necessary in this case. I assume that Connection() returns a connection but your did not provide a variable to hold the connection.
Pass the Select statement and the connection directly to the constructor of the command.
You have consumed all the data you returned in the While loop. If you only only need the Count then ask for the Count and use .ExecuteScalar.
I don't see the point of the If because the if portion is identical to the else portion.
An empty Catch just swallows errors. Bad idea.
Private Sub OPCode()
Dim CountReturned As Integer
Try
'Call Connection()
Using cn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand("select Count(*) from medicine where expiry_date < date_sub(now(), interval 3 month);", cn)
cn.Open()
CountReturned = CInt(cmd.ExecuteScalar)
End Using
End Using
If CountReturned = 1 Then
pop.Image = Image.FromFile("E:\asasda.png")
pop.TitleText = "Notification Alert!!!"
pop.ContentText = "Medicine at Risk"
pop.AnimationDuration = 3000
pop.Popup()
Else
pop.Image = Image.FromFile("E:\asasda.png")
pop.TitleText = "Notification Alert!!!"
pop.ContentText = "No items for risk"
pop.AnimationDuration = 3000
pop.Popup()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
If you cannot get the MySql data_sub working then use vb and parameters.
Using cmd As New MySqlCommand("select Count(*) from medicine where expiry_date < #Minus3Months;", cn)
cmd.Parameters.Add("#Minus3Months", MySqlDbType.DateTime).Value = Now.AddMonths(-3)
cmd.CommandText = "select * from medicine where expiry_date < #threeMonthsAgo"
cmd.parameters.add("#threeMonthsAgo", variableWithYourDate)
You can pass in a value from VB using parameters.

Insert a specific date in Mysql using vb.net

Okay here is the scenario, I need to insert a specific date in mysql. Everytime I insert this date I get 0000-00-00.
Everytime a user pays between the 1st and the 20th of the month then the wb_due-date column would increment the month by 1
Ex.
I have a default value of wb_paid-date = 2013-10-15 and wb_due-date = 2013-10-20.
Now User1 Paid on 2013-10-15 and after I clicked button, the date saved on wb_due-date was 0000-00-00 instead of 2013-11-20
Take a look at my code
Function iterate(ByVal d As Date) As String
Dim m As Integer = d.Month
If d.Month >= 1 And d.Month <= 11 Then
m += 1
ElseIf d.Month = 12 Then
m = 1
End If
Return m
End Function
cmd = New MySqlCommand("INSERT INTO tbl_billing(wb_paid-date, wb_due-date)
VALUES(CURDATE(), iterate(Now.Date) , con)
First, let's fix your function:
Function iterate(ByVal d As DateTime) As String
Return d.AddMonths(1).ToString("yyyy-MM-dd")
End Function
Also, if you're putting a string date into command, you're almost certainly doing something wrong. Let's just do this:
Function iterate(ByVal d As DateTime) As DateTime
Return d.AddMonths(1)
End Function
Then we'll fix your Sql Command:
cmd = New MySqlCommand("INSERT INTO tbl_billing(wb_paid-date, wb_due-date) VALUES(CURDATE(), ? " , con)
cmd.Parameters.Add("?", SqlDbType.DateTime).Value = iterate(Today)

Why would AccessDataSource return different results to query in Access?

I have a query to return random distinct rows from an Access database. Here is the query:
SELECT * FROM
(SELECT DISTINCT m.MemberID, m.Title, m.FullName, m.Address,
m.Phone, m.EmailAddress, m.WebsiteAddress FROM Members AS m INNER JOIN MembersForType AS t ON m.MemberID = t.MemberID WHERE
(Category = 'MemberType1' OR Category = 'MemberType2')) as Members
ORDER BY RND(members.MemberID) DESC
When I run this in Access it returns the rows in different order every time, as per the random sort order. When I run it through my web app however the rows return in the same order every time. Here is how I call it in my code-behind:
private void BindData()
{
using (AccessDataSource ds = new AccessDataSource("~/App_Data/mydb.mdb", GetSQLStatement()))
{
ds.DataSourceMode = SqlDataSourceMode.DataReader;
ds.CacheDuration = 0;
ds.CacheExpirationPolicy = DataSourceCacheExpiry.Absolute;
ds.EnableCaching = false;
listing.DataSource = ds.Select(new DataSourceSelectArguments());
listing.DataBind();
if (listing.Items.Count == 0)
noResults.Visible = true;
else
noResults.Visible = false;
}
}
I added in all that stuff about caching because I thought maybe the query was being cached but the result was the same. I put a breakpoint in the code to make sure the query was the same as above and it was.
Any ideas? This is driving me nuts.
When executing the ACE/Jet RND function against a new connection the same seed value is used each time. When using MS Access you are using the same connection each time, which explains why you get a different value each time.
Consider these VBA examples: the first uses a new connection on each iteration:
Sub TestDiff()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;Data " & _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Tempo\Test_Access2007.accdb"
.CursorLocation = 3
Dim i As Long
For i = 0 To 2
.Open
Debug.Print .Execute("SELECT RND FROM OneRowTable;")(0)
.Close
Next
End With
End Sub
Output:
0.705547511577606
0.705547511577606
0.705547511577606
Note the same value each time.
The second example uses the same connection on each iteration (the .Open and .Close statements are relocated outside the loop):
Sub TestSame()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;Data " & _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Tempo\Test_Access2007.accdb"
.CursorLocation = 3
.Open
Dim i As Long
For i = 0 To 2
Debug.Print .Execute("SELECT RND FROM OneRowTable;")(0)
Next
.Close
End With
End Sub
Output:
0.705547511577606
0.533424019813538
0.579518616199493
Note different values each time.
In VBA code you can use the Randomize keyword to seed the Rnd() function but I don't think this can be done in ACE/Jet. One workaround is to use the least significant decimal portion of the ACE/Jet the NOW() niladic function e.g. something like:
SELECT CDBL(NOW()) - ROUND(CDBL(NOW()), 4) FROM OneRowTable
I would move the RND into the inner SELECT
SELECT * FROM
(SELECT DISTINCT m.MemberID, RND(m.MemberID) as SortOrder, m.Title,
m.FullName, m.Address, m.Phone, m.EmailAddress, m.WebsiteAddress
FROM Members AS m
INNER JOIN MembersForType AS t ON m.MemberID = t.MemberID
WHERE
(Category = 'MemberType1' OR Category = 'MemberType2')) as Members
ORDER BY
Members.SortOrder DESC
You can use time as one argument to the RND field
Dim Now As DateTime = DateTime.Now
Dim millSec As Integer = Now.Millisecond
finalQuery = "SELECT * FROM wordInfo ORDER BY Rnd(-(1000* ROUND(" + millSec.ToString("N") + ", 0)) * [ID])"
So here from date and time value, millisecond value is taken which will be integer and it is used in sql query by rounding it.
wordInfo is table name
ID is the column name in database table
This gives random order every time (since millisecond value is different) be it same connection or new connection.