Autogenerate Alphanumeric ID in vb.net - mysql

I need a help. i want to auto generate alphanumeric ID example A/001/2016 where 001 should be increment by 1 and 2016 represent year using vb 2010
i want like A/001/2016, A/002/2016, A/003/2016
This is my code:
Private Sub autogenerate_ID()
Dim mysqlconnection As MySqlConnection
Dim command As New MySqlCommand
MySqlConnection = New MySqlConnection()
MySqlConnection.ConnectionString = " server = localhost; user id = root; password=; database = birth_and_death "
Command.Connection = MySqlConnection
mysqlconnection.Open()
Dim sqlquery = "select Max(Death_ID) from decease "
command.CommandText = sqlquery
Dim ID As Integer
Dim value As String
Dim d As String = DateTime.Now.ToString("yyyy")
value = command.ExecuteScalar().ToString()
If String.IsNullOrEmpty(value) Then
value = "D/001/1990"
End If
value = value.Substring(3)
Int32.TryParse(value, ID)
ID = ID + 1
value = "D/" + ID.ToString("D3") + "/" + d
' value = "A/" + Convert.ToString(ID) + "/" + d
TxtDeathID.Text = value
command.Dispose()
mysqlconnection.Close()
mysqlconnection.Dispose()
End Sub

Try this :
If IsDBNull(Command.ExecuteScalar) = False Then
Dim t() As String = Split_Serie(Command.ExecuteScalar)
Value = "A/" & Format(t(1) + 1, "000") + "/" & Year(Now.Date)
Else
value = "D/001/1990"
End If
and you must create a function that split your cod as :
Public Function Split_Serie(num As String) As String()
Dim t() As String
t = Split(num, "/")
'Part1 = t(0)
'Part2 = t(1)
'Part2 = t(3)
Return t
End Function

Related

VB.Net Function Return MySql Results Two Dimensional Array

The following code pulls data from a MySql connection and returns the array (output).
This two dimensional array only works when the number of rows and columns are specified before running the query.
Is there a way to get around this? A non-fixed array size?
Please help!
Public Function GetUsers() As String(,)
Dim GetCommand As MySqlCommand
Dim SQL As String = "Select * From users"
Dim output(,) As String
Dim intRowCount As Integer = 2
Dim intColumnCount As Integer = 3 ' Users Count
ReDim output(intColumnCount - 1, intRowCount - 1)
Dim GetMyConn As New MySqlConnection
GetMyConn.ConnectionString = "server = mysql.com;user id=rtest;password=test1234;database=rtestdb;"
GetMyConn.Open()
GetCommand = New MySqlCommand(SQL, GetMyConn)
Dim counter As Integer = 0
Try
Dim getResult As Object = GetCommand.ExecuteReader()
While getResult.Read()
output(counter, 0) = getResult("username").ToString()
output(counter, 1) = getResult("game_ip").ToString()
counter = counter + 1
End While
Catch e As MySqlException
MessageBox.Show("There was an error accessing your data. DETAIL: " & e.ToString())
End Try
GetMyConn.Close()
Return output
End Function
'''
Use this instead
output(counter, 0) = getResult.GetString(0)
output(counter, 1) = getResult.GetString(1)
When you have integer use
reader.GetInt32(0)
and so on
To get the correct dimensions for your array
Change your select statement like below
Dim SQL As String = "Select (SElECT Count(*) rowcount FROM users),* From users"
So you have in your result table a column more with the row count in every row.
Now to redim your array. the Columncount you should know. Else you have to add also
,(SELECT count(*) FROM information_schema.columns
WHERE table_name ='users') columncount
So and then you have to adept your datareader
Try
Dim getResult As Object = GetCommand.ExecuteReader()
If getResult.Read() Then
ReDim output(intColumnCount - 1, Integer.Parse(getResult("rowcount ")) - 1)
output(0, 0) = getResult("username").ToString()
output(0, 1) = getResult("game_ip").ToString(
counter += 1
While getResult.Read()
output(counter, 0) = getResult("username").ToString()
output(counter, 1) = getResult("game_ip").ToString()
counter = counter + 1
End While
END IF
Catch e As MySqlException
MessageBox.Show("There was an error accessing your data. DETAIL: " & e.ToString())
End Try
The idea is to get the first row, catch rowcount and redimension the array properly with the right diemnsions. As described you can if you want do the same with with thecoumnsnumber, if you want to be even more flexible.
I have given three different options using different data structures. Most databse objects need to be closed and disposed. Using...End Using blocks take care of this. You want to do as little as possible while the connection is open.
'Option 1 Using DataTable
Public Function GetUsers() As DataTable
Dim dt As New DataTable
Using GetMyConn As New MySqlConnection("server = mysql.com;user id=rtest;password=test1234;database=rtestdb;"),
GetCommand As New MySqlCommand("Select * From users", GetMyConn)
GetMyConn.Open()
dt.Load(GetCommand.ExecuteReader)
End Using
Return dt
End Function
'Option 2 Using List(Of User)
Public Class User
Public Property ID As Integer
Public Property Name As String
Public Property GameIP As String
Public Sub New(UserID As Integer, UName As String, UGame As String)
ID = UserID 'Assumed there was a primary key ID of some sort
Name = UName
GameIP = UGame
End Sub
End Class
Public Function GetUsers() As List(Of User)
Dim lst As New List(Of User)
Using GetMyConn As New MySqlConnection("server = mysql.com;user id=rtest;password=test1234;database=rtestdb;"),
GetCommand As New MySqlCommand("Select * From users", GetMyConn)
GetMyConn.Open()
Using r = GetCommand.ExecuteReader
While r.Read
Dim u = New User(r.GetInt32(0), r.GetString(1), r.GetString(2))
lst.Add(u)
End While
End Using
End Using
Return lst
End Function
'Option 3 Using 2D array
Public Function GetUsers() As String(,)
Dim Users(,) As String = Nothing
Dim dt As New DataTable
Using GetMyConn As New MySqlConnection("server = mysql.com;user id=rtest;password=test1234;database=rtestdb;"),
GetCommand As New MySqlCommand("Select username, game_ip From users", GetMyConn)
GetMyConn.Open()
dt.Load(GetCommand.ExecuteReader)
End Using
ReDim Users(dt.Rows.Count - 1, 1)
For r = 0 To dt.Rows.Count - 1
Users(r, 0) = dt(r)(0).ToString
Users(r, 1) = dt(r)(1).ToString
Next
Return Users
End Function
The easiest way is:
Friend Function getDataAsArray() As Array
Try
Dim SQLConnection = New SqlConnection("server = mysql.com;user id=rtest;password=test1234;database=rtestdb;")
Dim DtTable As New DataTable
Dim mSqlAdapter As New SqlClient.SqlDataAdapter With {
.SelectCommand = New SqlCommand("Select * From yourtable", SQLConnection)
}
mSqlAdapter.Fill(DtTable)
Dim output As Array = (From twoColumns As DataRow In DtTable
Select col1 = twoColumns.Item("username"),
col2 = twoColumns.Item("game_ip")).ToList.ToArray
Return output
Catch ex As Exception
Console.WriteLine("Ops ops ops something wrong: " + ex.ToString)
End Try
Return Nothing
End Function

Mysql Replace function issue

I want to update my table with replace function, but the result is not my expected result, how can I solve this problem?
Lets say I have a LONGTEXT columns(using_id) with value like this 1,2,3,4,5,6,7,8,9,10,11,
Now I want to remove '1,' so I write in this way:-
Dim query As String = "UPDATE curr_id SET using_id = REPLACE(using_id,'" & $"{g_currTicketID}," & "','')"
But the result become 2,3,4,5,6,7,8,9,10,1 How can I keep my '11,'?
Expected result: 2,3,4,5,6,7,8,9,10,11,
Public Sub TicketStatusUpdate(p_str As String)
'Login => GET NEXT ID > UPDATE USING ID > UPDATE NEXT ID
'Sales => RELEASE > UPDATE USED ID > GET NEXT ID > UPDATE USING ID > UPDATE NEXT ID
Select Case p_str
Case "UPDATE USED ID"
TicketStatusUpdate("RELEASE")
Dim query As String = "UPDATE curr_id SET used_id = CONCAT(used_id, '" & $"{g_currTicketID}," & "')"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
TicketStatusUpdate("GET NEXT ID")
Case "GET NEXT ID"
Dim query_select = "SELECT * FROM curr_id WHERE DATE(curr_date) = '" & Format(DateTime.Today.Date, "yyyy-MM-dd") & "' "
Dim reader As MySqlDataReader
Dim IsNewDay As Boolean = False
Using cmd = New MySqlCommand(query_select, conn)
reader = cmd.ExecuteReader
reader.Read()
If reader.HasRows Then
g_currTicketID = reader.GetInt32("next_id")
Else
g_currTicketID = 1
IsNewDay = True
End If
reader.Close()
End Using
If IsNewDay Then TicketStatusUpdate("RESET")
TicketStatusUpdate("UPDATE USING ID")
TicketStatusUpdate("UPDATE NEXT ID")
Case "UPDATE USING ID"
Dim query As String = "UPDATE curr_id SET using_id = CONCAT(using_id, '" & $"{g_currTicketID}," & "')"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
Case "UPDATE NEXT ID"
Dim query1 As String = "SELECT * FROM curr_id"
Dim str_usingID As String = ""
Dim str_usedID As String = ""
Dim reader As MySqlDataReader
Using cmd = New MySqlCommand(query1, conn)
reader = cmd.ExecuteReader
reader.Read()
str_usingID = reader.GetString("using_id").ToString
str_usedID = reader.GetString("used_id").ToString
reader.Close()
End Using
Dim str_allID As String = (str_usingID + str_usedID).TrimEnd(",")
Dim strArray As String() = str_allID.Split(",")
Dim intArray As Integer() = Array.ConvertAll(strArray, Function(s) Int32.Parse(s))
Array.Sort(Of Integer)(intArray)
Dim nextID As Integer = FirstMissing(intArray)
Dim query2 As String = "UPDATE curr_id SET next_id = '" & nextID & "'"
Using cmd = New MySqlCommand(query2, conn)
cmd.ExecuteNonQuery()
End Using
Case "RELEASE"
Dim query As String = "UPDATE curr_id SET using_id = REPLACE(using_id,'" & $"{g_currTicketID}," & "','')"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
Case "RESET"
Dim query As String = "UPDATE curr_id SET next_id='',used_id='',using_id=''"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
End Select
End Sub
Private Function FirstMissing(sequence() As Integer) As Integer
Dim seq = sequence
Dim firstMissingNumer = Int32.MinValue
For i = 1 To Math.Min(seq.Last, seq.Count)
If seq(i - 1) <> i Then
firstMissingNumer = i
Exit For
End If
Next
If firstMissingNumer = Int32.MinValue Then
Return seq.Max + 1
Else
Return firstMissingNumer
End If
End Function
When I logout the application it will call TicketStatusUpdate("RELEASE") to remove the g_currTicketID from using_id column.
Examples:
g_currTicketID = 1
using_id = 1,11,21,31,
When TicketStatusUpdate("RELEASE") called it will remove all '1,' from using_id, so the result will become 1,2,3 which is not the result that I want, I only want to remove '1,' and keep '11,21,31,'
Instead of replace just value, you could try to replace both value and boundary character
(in your case, comma ',' is a boundary character).
Example:
With g_currTicketID = 1, using_id = 1,11,21,31, then
replaceValue = CONCAT(',',g_currTicketID,',') = ',1,'
stringToReplace = CONCAT(',',using_id,',') = ',1,11,21,31,'
using_id = TRIM(BOTH ',' FROM REPLACE(stringToReplace, replaceValue, ','))
Your updat statement could be like this
Dim query As String = "UPDATE curr_id SET using_id = TRIM(BOTH ',' FROM REPLACE(CONCAT(',' ,using_id, ','), '," & $"{g_currTicketID}," & "', ','))"

select columns with not null property

I am looking for a way to select columns with a not null property and store it on to an ArrayList.
I have searched many threads for an answer but no luck.
I created a function which allows me to read data from a table but the problem is I don't know how do I get it to read the column name with a not null property. Here is the code that I tried
Public Function getNull(ByVal table As String) As ArrayList
Dim col_names As String = New String(getNames(table))
Dim nullColumns As ArrayList = New ArrayList
Dim dtreader As MySqlDataReader
Dim conn As MySqlConnection
Dim strConn As String
strConn = withDatabase
conn = New MySqlConnection(strConn)
Try
Dim cmd = New MySqlCommand("SELECT * FROM " & table & " WHERE " & col_names & " IS NOT NULL", conn)
conn.Open()
dtreader = cmd.ExecuteReader()
While dtreader.Read
'Get column names with not null property'
End While
Catch ex As Exception
MsgBox("Error " + ex.ToString, MsgBoxStyle.Critical)
End Try
Return nullColumns
End Function
Public Function getNames(ByVal table As String) As String
Dim conn As MySqlConnection
Dim strConn As String
Dim names As New String("")
strConn = withDatabase
conn = New MySqlConnection(strConn)
Using conn
conn.Open()
Dim dt = conn.GetSchema("Columns", New String() {Nothing, Nothing, table})
For Each row In dt.Rows
names += row("COLUMN_NAME") + " AND "
Next
names = names.Remove(names.Length - 4)
End Using
conn.Close()
Return names
End Function
The other threads I found was to find null values in a column, which is not I was looking for.

ds.tables(0) = 'ds.tables(0)' threw an exception of type 'System.NullReferenceException' vb.net

Im trying to pull data from 2 different tables in one button click event. I've checked over everything and doesn't seem to be any typo's or anything but keep getting this error.
Below is my code for the button click event
Protected Sub btnFindRepair_Click(sender As Object, e As EventArgs) Handles btnFindRepair.Click
Dim connection As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\ITrepair.mdf;Integrated Security=True")
Dim command As New SqlCommand("SELECT * from Repair; SELECT * FROM Customer WHERE Tracking_Number = #Tracking_Number", connection)
command.Parameters.Add("#Tracking_Number", SqlDbType.Int).Value = txtTrackingNumber.Text
Dim adapter As New SqlDataAdapter(command)
Dim ds As System.Data.DataSet
Dim table As New DataTable()
adapter.Fill(table)
'Repair Details
DDLBookedInBy.SelectedItem.Text = ""
DDLDeviceType.SelectedItem.Text = ""
txtBookedInDate.Text = ""
txtDeviceName.Text = ""
DDLAccessories.SelectedItem.Text = ""
txtDevicePassword.Text = ""
DDLRepairType.Text = ""
txtTechnical.Text = ""
txtCompletedNotes.Text = ""
DDLRepairStatus.Text = ""
'Customer Details
txtFname.Text = ""
txtLname.Text = ""
txtContactNum.Text = ""
txtAltContactNum.Text = ""
txtAddress.Text = ""
If table.Rows.Count() > 0 Then
' return only 1 row
DDLBookedInBy.SelectedItem.Text = ds.tables(0).Rows(0)(2).ToString()
DDLDeviceType.SelectedItem.Text = ds.tables(0).Rows(0)(3).ToString()
txtBookedInDate.Text = ds.tables(0).Rows(0)(4).ToString()
txtDeviceName.Text = ds.tables(0).Rows(0)(5).ToString()
DDLAccessories.SelectedItem.Text = ds.tables(0).Rows(0)(6).ToString()
txtDevicePassword.Text = ds.tables(0).Rows(0)(7).ToString()
DDLRepairType.Text = ds.tables(0).Rows(0)(8).ToString()
txtTechnical.Text = ds.tables(0).Rows(0)(9).ToString()
txtCompletedNotes.Text = ds.tables(0).Rows(0)(10).ToString()
txtFname.Text = ds.tables(1).Rows(1)(4).ToString()
txtLname.Text = table.Rows(1)(5).ToString()
txtContactNum.Text = table.Rows(1)(6).ToString()
txtAltContactNum.Text = table.Rows(1)(7).ToString()
txtAddress.Text = table.Rows(1)(8).ToString()
Else
MsgBox("NO DATA found")
End If
End Sub
Replace all occurences of ds.tables(0) with table. You haven't initialized the DataSet ds but you don't need it anyway because you fill the DataTable tbl with adapter.Fill(table).
For example:
If table.Rows.Count > 0 Then
DDLBookedInBy.SelectedItem.Text = table.Rows(0)(2).ToString()
' .... '
If you want to fill the DataSet use:
Dim ds As System.Data.DataSet
Dim table As New DataTable()
ds = New DataSet()
adapter.Fill(ds)
If table.Rows.Count > 0 Then
DDLBookedInBy.SelectedItem.Text = ds.Tables(0).Rows(0)(2).ToString()
' .... '
txtFname.Text = ds.Tables(1).Rows(1)(4).ToString()
' ... '

Importing contents of text file into MySQL using VB.Net

Good day everyone. I am trying to create a program that will transfer all of the contents of a text file into a database. So far, my code works, but my code only inserts the first line of the text file into the database. What should I add to solve the problem? I am noob at programming sorry.
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim filename As String = "C:\Users\user\desktop\swipe.txt"
Dim Query As String
Dim data As String = System.IO.File.ReadAllText(filename)
Dim Loc, _date, time, temp, id As String
Loc = data.Substring(0, 3)
_date = data.Substring(3, 8)
time = data.Substring(11, 4)
temp = data.Substring(15, 3)
id = data.Substring(18, 3)
Query = "INSERT INTO tbl_entrance_swipe VALUES ('" + Loc + "','" + _date + "','" + time + "','" + temp + "','" + id + "')"
Dim con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
Try
con.Open()
Dim sql As MySqlCommand = New MySqlCommand(Query, con)
sql.ExecuteNonQuery()
MsgBox("Record is Successfully Inserted")
con.Close()
Catch ex As Exception
con.Close()
MsgBox("Record is not Inserted" + ex.Message)
End Try
End Sub
End Class
You are using File.ReadAllText which reads the complete text of the file. You want to read line by line, therefore you can use File.ReadLines(deferred executed) or File.ReadAllLines(reads all into a String()).
You should also use sql-parameters to prevent sql-injection and incorrect implicit type conversions or localization issues. Finally, use the Using statement to ensure that all unmanaged resources are disposed (f.e. the connection gets closed even on error):
Dim filename As String = "C:\Users\user\desktop\swipe.txt"
Dim allLines As String() = File.ReadAllLines(filename)
Dim query As String = "INSERT INTO tbl_entrance_swipe VALUES (#Loc, #Date, #Time, #Temp, #Id)"
Using con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
con.Open()
Using cmd As New MySql.Data.MySqlClient.MySqlCommand(query, con)
For Each line In allLines
Dim loc, dt, time, temp, id As String
loc = line.Substring(0, 3)
dt = line.Substring(3, 8)
time = line.Substring(11, 4)
temp = line.Substring(15, 3)
id = line.Substring(18, 3)
cmd.Parameters.Clear()
Dim pLoc As New MySql.Data.MySqlClient.MySqlParameter("#Loc", MySqlDbType.VarChar)
pLoc.Value = loc
cmd.Parameters.Add(pLoc)
Dim pDate As New MySql.Data.MySqlClient.MySqlParameter("#Date", MySqlDbType.VarChar)
pDate.Value = dt
cmd.Parameters.Add(pDate)
Dim pTime As New MySql.Data.MySqlClient.MySqlParameter("#Time", MySqlDbType.VarChar)
pTime.Value = time
cmd.Parameters.Add(pTime)
Dim pTemp As New MySql.Data.MySqlClient.MySqlParameter("#Temp", MySqlDbType.VarChar)
pTemp.Value = temp
cmd.Parameters.Add(pTemp)
Dim pId As New MySql.Data.MySqlClient.MySqlParameter("#Id", MySqlDbType.VarChar)
pId.Value = id
cmd.Parameters.Add(pId)
cmd.ExecuteNonQuery()
Next
MsgBox("All records were inserted successfully")
con.Close()
End Using
End Using