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
Related
I'm making a tool to help a company with there staff holiday (staff holiday calculator)
I connected myself by vb and its connection to the database but I can't get any result
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New api()
Dim adapter As New MySqlDataAdapter()
Dim table As New DataTable()
Dim command As New MySqlCommand("SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'", conn.getConnection())
command.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Try
conn.getConnection.Open()
adapter.SelectCommand = command
adapter.Fill(table)
Dim sqlReader As MySqlDataReader = command.ExecuteReader()
While sqlReader.Read()
namee = sqlReader("Full_Name").ToString()
job = sqlReader("Job").ToString()
days = sqlReader("Free_Days").ToString()
MsgBox(sqlReader("Full_Name").ToString())
End While
Label2.Text = "Name : " + namee
Label3.Text = "Job : " + job
Label8.Text = "Holiday Free Days : " & days
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End Try
End Sub
I didn't get any MsgBox and there is no error and the label text didn't change
I don't have MySQL, but based on MSSQL try something like this:
Dim namee, job, days As String
Dim commandText As String = "SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'"
Dim conn As New api()
Using adapter As New MySqlDataAdapter(commandText, conn.getConnection())
adapter.SelectCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count = 0 Then
MessageBox.Show("No rows found", "ERROR")
Else
With table(0)
namee = .Item("Full_Name")
job = .Item("Job")
days = .Item("Free_Days")
End With
End If
End Using
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.
I'm working on my project which displays a list of employee. here, the information and picture of the employee will be shown. my project can now show the list of employees in the listbox and when I double click on an employee, his/her profile will be shown on a textbox. my problem is that i can't make their pictures to show in the picturebox. I already stored their picture on a table in my database along with their id, name, and profile. It only shows the picture of the first employee on the table. can anybody help me?
here's what I already done:
I populated the listbox:
Call Connect()
With Me
STRSQL = "Select employee_name from Employees"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
reader.Close()
adptr.SelectCommand = myCmd
adptr.Fill(dt)
lstEmployee.DisplayMember = "employee_name"
lstEmployee.ValueMember = "employee_id"
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
lstEmployee.Items.Add(dt.Rows(i)("employee_name"))
Next
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
here's how I show the info on textbox
Dim FileSize As UInt32
Dim mStream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mStream.GetBuffer()
FileSize = mStream.Length
Dim cmd As New MySqlCommandBuilder
Call Connect()
With Me
STRSQL = "select employee_name, profile from Employees where employee_id = " & lstEmployee.SelectedIndex
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
txtName.Text = reader("employee_name")
txtProfile.Text = reader("profile")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
adptr.SelectCommand = myCmd
dt = New DataTable
adptr = New MySqlDataAdapter("select picture from Employees", myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
You miss the where clause is must be like to search a one employee to view there image.
adptr = _
New MySqlDataAdapter("select picture from Employees " + _
"where employee_id = " & lstEmployee.SelectedIndex, myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
P.S.: You must study the LINQ (Language-Integrated Query) for better approach.
In my application customers book vehicle online & admin of site assigns duty to drivers which are already added. Below screen shot you can see the list of drivers.
Now what I am trying to do is if admin assigns some duty to some driver then in assign duty column should count which driver get how many duties. e.g. if admin assign duty to first driver then duty assign column should be updated by 1. Is it possible to do so? Below my code to assign duty to drivers
VB
Protected Sub assignDuty_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles assignDuty.Click
Dim Did As String
Did = DriversList.SelectedItem.ToString
Try
Dim str1 As String = "UPDATE newBooking SET Assigned = '" & Did & "', status = 'Approved', DriverContact = '" + driverMobile.Text + "', vehicleNo = '" + vehicleNo.Text + "' WHERE Bid = '" & trackInput.Text + "'"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
data = command.ExecuteReader
con.Close()
send_customer_message()
send_driver_message()
customer_confirm_mail()
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Protected Sub DriversList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DriversList.SelectedIndexChanged
Try
Dim str As String = "SELECT * FROM addDriver where DriverID='" + DriversList.SelectedValue.ToString + "';"
con.Open()
Dim cmd As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
con.Close()
orderStatus.Visible = True
additionalDetail.Visible = True
vehicleNo.Text = dt.Rows(0)("VehicleRegistration").ToString
driverName.Text = dt.Rows(0)("DriverName").ToString
driverMobile.Text = dt.Rows(0)("contact")
'duration.Text = dt.Rows(0)("duration")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
UPDATE!
How admin assigns duty to drivers.
Admin receives mail when customer books online. He simply enters booking ID & click track orders & all details will be displayed in left side part. In right side he has list of drivers & he selects one & on select last section vehicle details get updated & finally he clicks on assign duty so databse get updated in newBooking table.
UPDATE!
Protected Sub assignDuty_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles assignDuty.Click
Try
Dim Did As String
Did = DriversList.SelectedItem.ToString
Dim Query1 As String
Query1 = "UPDATE newBooking SET Assigned = '" & Did & "', status = 'Approved', DriverContact = '" + driverMobile.Text + "', vehicleNo = '" + vehicleNo.Text + "' WHERE Bid = '" & trackInput.Text + "'"
RunCommand(Query1)
Dim Query2 As String
Query2 = "UPDATE addDriver SET [DutyAssigned] = [DutyAssigned] + 1 WHERE DriverID = " & Did
RunCommand(Query2)
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Public Function RunCommand(ByVal myQry As String) As String
Try
Using _conn As New MySqlConnection("constr")
Using _comm As New MySqlCommand()
With _comm
.Connection = _conn
.CommandText = myQry
.CommandType = CommandType.Text
End With
_conn.Open()
_comm.ExecuteNonQuery()
End Using
End Using
RunCommand = ""
Catch ex As Exception
RunCommand = ex.Message
End Try
End Function
[![enter image description here][4]][4]
Check below code. Here you need to specify your connection string in RunCommand method. Let me know the results.
Protected Sub assignDuty_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles assignDuty.Click
Try
Dim Did As String
Did = DriversList.SelectedItem.ToString
Dim DriverID As String
DriverID = DriversList.SelectedValue
Dim Query1 As String
Query1 = "UPDATE newBooking SET Assigned = '" & Did & "', status = 'Approved', DriverContact = '" + driverMobile.Text + "', vehicleNo = '" + vehicleNo.Text + "' WHERE Bid = '" & trackInput.Text + "'"
RunCommand(Query1)
Dim Query2 As String
Query2 = "UPDATE addDriver SET DutyAssigned = DutyAssigned + 1 WHERE DriverID = " & DriverID
RunCommand(Query2)
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Public Function RunCommand(ByVal myQry As String) As String
Try
Using _conn As New MySqlConnection("connectionStr here")
Using _comm As New MySqlCommand()
With _comm
.Connection = _conn
.CommandText = myQry
.CommandType = CommandType.Text
End With
_conn.Open()
_comm.ExecuteNonQuery()
End Using
End Using
RunCommand = ""
Catch ex As Exception
RunCommand = ex.Message
End Try
End Function
I would encourage you to use binding parameters instead of concatinating query string (like SELECT * FROM addDriver where DriverID=:DriverId and cmd.Parameter.Add("DriverId",MySqlType.Varchar,<fieldLength>,"DriverId". Do it also in the Update query.)
In assignDuty_Click you should use UpdateCommand instead of SelectCommand (I´m no MySql pro but SelectCommand smells for me).
For updating the Duty Assigned field enhance the Update string in assignDuty_Click with SET DutyAssigned = DutyAssigned + 1 ... (or whatever the field is named in newBooking).
I've searched different forums on this one, but still no luck.
I have tried different codes, so far my query looks like this:
Dim query As String
query = "LOAD DATA LOCAL INFILE 'C:\swipeimport\A1_20130513.txt' INTO TABLE tbl_entrance_swipe (#var1)" & _
"SET Loc=SUBSTRING(#var1,1,3)," & _
"date=SUBSTRING(#var1,4,8)," & _
"time=SUBSTRING(#var1,12,3)," & _
"temp=SUBSTRING(#var1,16,3)," & _
"id=SUBSTRING(#var1,19,10);"
con.Open()
Dim sql As MySqlCommand = New MySqlCommand(query, con)
Dim i As Integer = sql.ExecuteNonQuery()
If (i > 0) Then
MsgBox("Record is Successfully Inserted")
Else
MsgBox("Record is not Inserted")
End If
con.Close()
I want to import the contents of a text file into table, my table has this fields:
Loc, date, time, temp, id.
The content of the text file looks like this:
K0720130514045501018006D9566
where the breakdown is as follows:
K07 ----> Loc
20130514 ----> date
0455 ----> time
010 ----> temp
18006D9566 ----> id
could you help, i cannot insert this in my table. What is the problem with my code?
It just give a fatal error. Please point me in the right direction. Any help is very much appreciated. Thank you.
EDIT:
Here is my connection string:
Dim con As MySqlConnection = New MySqlConnection("Data Source=dev;Database=mydb;User ID=root;Password=mypass;")
Try like below, It will help you....
Dim filename As String = "C:\swipeimport\A1_20130513.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, 9)
Query = "INSERT INTO tbl_entrance_swipe VALUES ('" + Loc + "','" + _date + "','" + time + "','" + temp + "','" + id + "')"
Dim con As MySqlConnection = New MySqlConnection("Data Source=dev;Database=mydb;User ID=root;Password=mypass;")
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