Is .ExecuteNonQuery() required to add sql data to a DB in vb.net - mysql

I am running the following code (part of it) to connect to PHPmyadmin DB
Private Sub sreg_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SqlConnection.ConnectionString = ServerString
Try
If SqlConnection.State = ConnectionState.Closed Then
SqlConnection.Open()
MsgBox("Successfully connected to MySQL DB")
Else
SqlConnection.Close()
MsgBox("Connection is Closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveNames(ByRef SQLStatment As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatment
.CommandType = CommandType.Text
.Connection = SqlConnection
.ExecuteNonQuery()
End With
SqlConnection.Close()
MsgBox("Succesfully Added!")
SqlConnection.Dispose()
End Sub
However the .ExecuteNonQuery() is giving me huge headaches in terms of errors and problems. It uploads the data but, it can only do it once (one upload) before, it returns an error.
When I remove the .ExecuteNonQuery() no data gets uploaded? So I guess it is necessary.
Here is the code im uploading (part of it)
sql = "INSERT INTO students(student_id, title, initial, surname,
street, city, pcode, country ) VALUES ('" & strStudent & "', '"
& vtital & "', '" & vinital & "', '" & vsurname & "', '" & vstreet
& "', '" & vcity & "', '" & vpcode & "', '" & vcountry & "' )"
SaveNames(sql)
Hope my question makes sense and that I can get the message across

There are some errors in your approach to save this data that could lead to your problem.
The first problem is that code doesn't use a parameterized query. This is a security concern (Sql Injection) but also a simple logical problem. If you concatenate strings to build a sql query you have a problem with strings that contains characters with a special meaning for the database sql engine. What if one of your strings contains a single quote? It will be seen as the end of the string with the remainder of your text as invalid sql.
The second problem is the lacking of open/close/dispose of the MySqlConnection also in case of exceptions. This is resolved by using the Using Statement.
So I would rewrite your method as
Public SaveNames(ByRef SQLStatment As String, List(Of MySqlParameter) parameters) As Integer
Using con = new MySqlConnection(... put here the connection string...)
Using cmd = New MySqlCommand(SQLStatment, con)
if parameters.Count > 0 Then
cmd.Parameters.AddRange(parameters.ToArray())
End If
return cmd.ExecuteNonQuery()
End Using
End Using
End Function
And call it with code like this
sql = "INSERT INTO students(student_id, title, initial, surname," & _
"street, city, pcode, country ) VALUES (#id,#title,#init,#sur," & _
"#street,#city,#pcode,#country)"
Dim ps = New List(Of MySqlParameters)()
Dim p = new MySqlParameter("#id", MySqlDbType.Int32).Value = Convert.ToInt32(strStudent)
ps.Add(p)
p = new MySqlParameter("#title", MySqlDbType.VarChar).Value = vtital
ps.Add(p)
.. and so on for the other parameters.
.. respecting the actual datatype on the database table
.....
SaveNames(sql, ps)

Try this ...
cmd = New MySqlCommand( sqlstatement, conn)
conn.open()
cmd.ExecuteNonQuery()
conn.Close()
And as I suggested you .. use parameterized

Related

how can i add a DateTimePicker and ComboBoxes to mysql database then displaying it to DataGridView

Form
Sub ViewRecords()
Try
read("SELECT * FROM reservation", DataGridView1)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub add_Click(sender As Object, e As EventArgs) Handles add.Click
Try
ComboTIME = (hr.SelectedItem.ToString + ":" + min.SelectedItem.ToString + " " + fr.SelectedItem.ToString)
write("INSERT INTO reservation (ReservationCode, UserId, RestaurantName, RestaurantLocation, Time, Date, ReservationStatus, Remarks) VALUES ('" & code.Text & "','" & userid.Text & "','" & restoname.Text & "', '" & restolocation.Text & "', '" & datepicker.Value & "', '" & ComboTIME & "', '" & ans & "', '" & remarks.Text & "')")
code.Clear()
userid.Clear()
restoname.Clear()
restolocation.Clear()
datepicker.ResetText()
hr.ResetText()
min.ResetText()
fr.ResetText()
y.ResetText()
n.ResetText()
remarks.Clear()
ViewRecords()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
MODULE CONNECTION
Public Sub read(ByVal sql As String, ByVal DTG As Object)
Try
dt = New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
da.SelectCommand = cmd
da.Fill(dt)
DTG.DataSource = dt
Catch ex As Exception
MessageBox.Show(ex.Message & ex.Source, "Load Data Failed")
con.Close()
End Try
con.Close()
da.Dispose()
End Sub
Public Sub write(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
result = cmd.ExecuteNonQuery
If result = 0 Then
MessageBox.Show("FAILED.")
Else
MessageBox.Show("SUCCESS.")
End If
End With
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
con.Close()
End Sub
My only problem in my program is that when i click the button the datetimepicker and the comboboxes that i bind and declared as ComboTIME wont record in the database and also in the datagridview, My connection with the database is fine and the TextBoxes were storable and displayable in both database and datagridview, can anyone help me with this problem?
Always provide accessibility modifiers to make your code clearer to read. When you start working in multimple languages in multiple evironments it might be difficult to remember whai the default accessibility is in vb.net.
Separate you data access code from your user interface code. For example, you are passing a DataGridView to your module code. Suppose the boss says he really wants to have a web app. Now you not only have to fix your user interface code but you need to modify your module too. Keeping them separate would only require changing the UI code. My DataAccess class remains the same.
Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
Parameters help protect against sql injection. A user can enter anything in a text box including "Delete * From reservation" Parameters provide only values not executable code so they cannot damage the database. I had to guess at the SqlDbType so, you need to check you database for the correct types.
User Interface code...
Private Sub ViewRecords()
Dim dt As DataTable = Nothing
Try
dt = DataAccess.GetReservationData
Catch ex As Exception
MsgBox($"Failed to fill grid {ex.Message}")
Return
End Try
DataGridView1.DataSource = dt
End Sub
Private ans As String = ""
Private Sub InsertReservation()
Dim code As Integer
If Not Integer.TryParse(code.Text, code) Then
MessageBox.Show("Code needs to be a number.")
Return
End If
Dim userID As Integer
If Not Integer.TryParse(userid.Text, userID) Then
MessageBox.Show("User ID needs to be a number.")
Return
End If
Try
DataAccess.InsertReservation(code, userID, restoname.Text, restolocation.Text, ComboTIME.Text, datepicker.Value, ans, remarks.Text)
Catch ex As Exception
MessageBox.Show($"Insert Failed {ex.Message}")
Return
End Try
MessageBox.Show("Reservation inserted successfully.")
End Sub
Database code...
Public Class DataAccess
Private Shared ConStr As String = "Your connection string"
Public Shared Function GetReservationData() As DataTable
Dim dt As New DataTable
Using con As New MySqlConnection(ConStr),
cmd As New MySqlCommand("SELECT * FROM reservation", con)
con.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Public Shared Sub InsertReservation(ReservationCode As Integer, UserID As Integer, RestaurantName As String, Location As String, Time As String, ResDate As Date, Status As String, Remarks As String)
Using con As New MySqlConnection(ConStr),
cmd As New MySqlCommand("INSERT INTO reservation (ReservationCode, UserId, RestaurantName, RestaurantLocation, Time, Date, ReservationStatus, Remarks) VALUES (#ResurvationCode, #UserID, #RestaurantName, #Location, #Time, #Date, #Status, #Remarks)", con)
With cmd.Parameters
.Add("#ReservationCode", MySqlDbType.Int32).Value = ReservationCode
.Add("#UserID", MySqlDbType.Int32).Value = UserID
.Add("#RestaurantName", MySqlDbType.VarChar).Value = RestaurantName
.Add("#Location", MySqlDbType.VarChar).Value = Location
.Add("#Time", MySqlDbType.VarChar).Value = Time
.Add("#Date", MySqlDbType.DateTime).Value = ResDate
.Add("#Status", MySqlDbType.VarChar).Value = Status
.Add("#Remarks", MySqlDbType.VarChar).Value = Remarks
End With
End Using
End Sub
End Class

SQL Connection error 40 000webhost with Visual Basic

I am pretty sure I have all of my information right here, but I keep getting this error
http://puu.sh/qoZDQ/7294d6e682.png
The code I used: (Not mine)
I have the right username password and database name (I think)
'SET THE CONNECTION BETWEEN VISUAL BASIC AND MYSQL DATABASE
Dim con As SqlConnection = New SqlConnection("Data Source=mysql9.000webhost.com;" & "Initial Catalog=databasename;" & "User ID=username;" & "Password=password;")
'A SET OF COMMAND IN MYSQL
Dim cmd As New SqlCommand
'SET A CLASS THAT SERVES AS THE BRIDGE BETWEEN A DATASET AND DATABASE FOR SAVING AND RETRIEVING DATA.
Dim da As New SqlDataAdapter
'SET A CLASS THAT CONSISTS SPECIFIC TABLE IN THE DATABASE
Dim dt As New DataTable
Dim sqlQuery As String
Dim result As Integer
Private Sub register(ByVal sqlQuery As String)
Try
'OPENING THE CONNECTION
con.Open()
'HOLDS THE DATA TO BE EXECUTED
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'EXECUTE THE DATA
Result = cmd.ExecuteNonQuery
'CHECKING IF THE DATA HAS BEEN EXECUTED OR NOT
If result > 0 Then
MsgBox("User has been registered.")
Else
MsgBox("Failed to register the user.")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub login(ByVal sqlQuery As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'FILLING THE DATA IN A SPECIFIC TABLE OF THE DATABASE
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
'DECLARING AN INTEGER TO SET THE MAXROWS OF THE TABLE
Dim maxrow As Integer = dt.Rows.Count
'CHECKING IF THE DATA IS EXIST IN THE ROW OF THE TABLE
If maxrow > 0 Then
MsgBox("Welcome " & dt.Rows(0).Item(4))
Else
MsgBox("Account does not exist.")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
Private Sub btn_Register_Click(sender As Object, e As EventArgs) Handles btn_Register.Click
sqlQuery = "INSERT INTO `dbuser` ( `user_name`, `user_username`, `user_pass`, `user_type`, `user_steamid`)" & "VALUES ('" & txtname.Text & "','" & txtusername.Text & "','" & txtpassword.Text & "','" & cbotype.Text & "','" & txtsteamid.Text & "')"
register(sqlQuery)
End Sub
Private Sub btn_Login_Click(sender As Object, e As EventArgs) Handles btn_Login.Click
sqlQuery = "SELECT * FROM `dbuser` WHERE user_username ='" & txtusername.Text & "' AND user_pass = '" & txtpassword.Text & "'"
login(sqlQuery)
End Sub
I used the database info from here http://puu.sh/qoZXo/a391cba854.jpg (Also not my info just an example so I dont post my info publicly)
I fixed my issue with the help of what Plutonix commented
MySql is not the same thing as Microsoft SqlServer – Plutonix
So I did some googling and found this: https://dev.mysql.com/downloads/connector/net/
This is the .Net framework for MySql (I think thats the right terms)
anyhow installing this then changing the top line of my code from
imports System.Data.SqlClient
To:
imports MySql.Data.MySqlClient
and changing the sql variables in the code to MySql variables by just adding My to the first bit, and it seems to work "better" I now have a new issue, but its with 000webhosts mysql database, not the code.

mysql vb.net There is already an open Data Reader associated with this connection

I've already added reader.dispose() but it's still showing the exception
There is already an open DataReader associated with this connection which must be closed first.
Please don't mind the Sql injection. I'll be fixing that soon.
Private Sub ItemStore(ByVal itemname)
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "select * from inventory where itemname = '" & itemname & "'"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader()
While reader.Read
AddItemstoDatabase(reader.GetString("itemcategory"), reader.GetString("itemname"), reader.GetString("price"), reader.GetString("stockcount"))
End While
reader.Close()
reader.Dispose()
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub AddItemstoDatabase(ByVal itemcategory, ByVal itemname, ByVal price, ByVal stock)
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Try
mydbcon.Open()
Dim Query As String
Query = "INSERT into itemstored(itemcategory, itemname, price, stockcount) VALUES('" & itemcategory & "', '" & itemname & "', '" & price & "', '" & stock & "')"
Dim rowsadded = COMMAND.ExecuteNonQuery()
If rowsadded = 0 Then
MessageBox.Show("Failed to update database")
End If
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Since your method ItemStore have already open connection for same connection string, and from same method again you calling another function AddItemstoDatabase which is also going to use same connection string.
Due to this reason you are getting this exception
There is already an open DataReader associated with this connection which must be closed first.
And you can't open multiple connection for same connection string without closing earlier open connection .
UPDATE
Not sure if it works in your scenario, try comment connection obj since it is global
Private Sub AddItemstoDatabase(ByVal itemcategory, ByVal itemname, ByVal price, ByVal stock)
'mydbcon = New MySqlConnection
'mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Try
'mydbcon.Open()
Dim Query As String
Query = "INSERT into itemstored(itemcategory, itemname, price, stockcount) VALUES('" & itemcategory & "', '" & itemname & "', '" & price & "', '" & stock & "')"
COMMAND.CommandText = Query
Dim rowsadded = COMMAND.ExecuteNonQuery()
If rowsadded = 0 Then
MessageBox.Show("Failed to update database")
End If
'mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Change:
mydbcon = New MySqlConnection
to:
Dim mydbcon = New MySqlConnection
and it will work.
You are using a globally declared connection variable there.
And as the error states, you can't have 2 data readers open in 1 connection at the same time.
So I was able to fix it by adding
COMMAND = New MySqlCommand(Query, mydbcon)
between the query and the COMMAND.ExecuteNonQuery()
Thank you all for the other answers!

Why do I keep getting this mysql error?

Hi stackoverflow people!
I have been recently developing a simple vb.net program that connects to a mysql database to register and login users with given credentials. I have used this code to register my users but I keep getting and error (below the code)
Dim insertUser As String = "INSERT INTO users(ID, username, password, email, verif)" _
& " VALUES('','" & Username.Text & "','" & Password.Text & "','" & Email.Text & "','" & currentRandString & "');"
Dim checkUsername As String = "SELECT * FROM users WHERE username='" & Username.Text & "'"
MysqlConn = New MySqlConnection()
MysqlConn.ConnectionString = mysqlconntxt4reg
MysqlConn.Open()
Dim myCommand As New MySqlCommand
myCommand.Connection = MysqlConn
myCommand.CommandText = checkUsername
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
myData.Close()
Else
myData.Close()
Dim myCommand2 As New MySqlCommand
myCommand2.Connection = MysqlConn
myCommand2.CommandText = insertUser
myAdapter.SelectCommand = myCommand2
Dim myData2 As MySqlDataReader
myData2 = myCommand2.ExecuteReader
Mail(Email.Text, currentRandString)
Me.Close()
myData2.Close()
End If
Catch myerror As MySqlException
MsgBox("Error While Connecting To Database:" & vbNewLine & vbNewLine & myerror.ToString, MsgBoxStyle.Critical, "Error")
Finally
MysqlConn.Dispose()
End Try
I have closed all my datareaders before opening other ones so I do not see why this does not work...
Error:
Link to Error Image
I would appreciate any help on this topic!
Thanks
Rodit
I would use the using statement around all the disposable objects to be sure that they release every references to the connection when they are no more needed, but looking at your code, I think you don't need at all the datareaders because you could resolve your problem just with the commands
Dim insertUser As String = "INSERT INTO users(username, password, email, verif)" _
& " VALUES(#p1, #p2,#p3,#p4)"
Dim checkUsername As String = "SELECT COUNT(*) FROM users WHERE username=#p1"
Using MysqlConn = New MySqlConnection(mysqlconntxt4reg)
Using myCommand = New MySqlCommand(checkUsername, MysqlConn)
MysqlConn.Open()
myCommand.Parameters.AddWithValue("#p1", Username.Text)
Dim result = myCommand.ExecuteScalar()
if result IsNot Nothing AndAlso Convert.ToInt32(result) > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
Else
Using myCommand2 = New MySqlCommand(insertUser, MysqlConn)
mycommand2.Parameters.AddWithValue("#p1",Username.Text)
mycommand2.Parameters.AddWithValue("#p2",Password.Text )
mycommand2.Parameters.AddWithValue("#p3",Email.Text)
mycommand2.Parameters.AddWithValue("#p4",currentRandString )
myCommand2.ExecuteNonQuery()
Mail(Email.Text, currentRandString)
End Using
End If
End Using
End Using
Of course I have replaced your string concatenations with a parameterized query. This is really an important thing to do to avoid Sql Injection
I have replaced the query that checks the user existence with a scalar operation that can be used with the command ExecuteScalar. Also, in the first query, it seems that you try to insert the field ID with an empty string. I think that the first field (ID) is an autonumber field and, in this case, you don't add it to the insert query and don't pass any value because the database will calculate that field for you.

how can i open execuete a query in VB while there is reader opened?

is there any possible way to execute this without getting this error "There is already an open DataReader associated with this Connection which must be closed first." i already tried using "dr.close()" and i get another error that says "Invalid attempt to Read when reader is closed." can you help me out?
Heres my code:
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Label2.Text = AllPicker1.Text
Label3.Text = AllPicker2.Text
If AllPicker1.Value >= AllPicker2.Value Then
MsgBox("End Date Must be Greater!")
Else
Dim SQLstatement As String = "SELECT * FROM tblStudInfo,tbl_studentLog WHERE tblStudInfo.StudID = tbl_studentLog.StudentNumber AND tbl_studentLog.LoginDate BETWEEN '" & AllPicker1.Text & "' AND '" & AllPicker2.Text & "'"
OpenData(SQLstatement)
End If
End Sub
Public Sub OpenData(ByRef SQLstatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLstatement
.CommandType = CommandType.Text
.Connection = SqlConnection
dr = .ExecuteReader()
End With
While dr.Read
Dim SQLstatementSave As String = "INSERT INTO tbl_report (RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate) VALUES ('" & dr("StudID") & "','" & dr("Name") & "','" & dr("Course") & "','" & dr("Dept") & "','" & dr("LoginTime") & "','" & dr("LoginDate") & "') "
dr.Close()
Save(SQLstatementSave)
End While
SqlConnection.Close()
SqlConnection.Dispose()
SqlConnection.Open()
End Sub
Public Sub Save(ByRef SQLstatementSave As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLstatementSave
.CommandType = CommandType.Text
.Connection = SqlConnection
.ExecuteNonQuery()
End With
SqlConnection.Close()
SqlConnection.Dispose()
SqlConnection.Open()
End Sub
End Class
It seems you are using only one SqlConnection. For most database systems you cannot reuse the connection while you are reading from it. You can either read all data into memory / DataTable and work on the rows after that or use a different SqlConnection for your Inserts.
When working with SqlConnections, Readers and Commands I find the Using Statement very helpful to visualize object usage and creation.
We can reduce this down to a single query:
INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
SELECT StudID, Name, Course, Dept, LoginTime, LoginDate
FROM tblStudInfo
INNER JOIN tbl_studentLog ON tblStudInfo.StudID = tbl_studentLog.StudentNumber
WHERE tbl_studentLog.LoginDate BETWEEN #StartDate AND #EndDate
Note the use of the full INNER JOIN syntax. The older TableA,TableB syntax for joins should be avoided. Also note the use of placeholders for your dates. This is important.
Now I need to draw attention to a couple functions I saw: OpenData(), and Save().
Those two functions are fundamentally broken, because they force you to build your queries in a way that leaves you vulnerable to sql injection hacking. Someday soon, someone will put a value like this into a textbox that is included with a query:
';DROP Table tbl_studentLog;--
Think carefully about what would happen now if someone entered that into your AllPicker1.Text. It would be hard to do that to a date picker, but I'll bet you have other plain text fields that would allow this. The first character (single quote) in my proposed input would close the string literal in the query. The second character (semi-colon) would end the individual statement, but sql server won't stop executing code. The next set of characters make up an additional statement that would drop your table. The final two characters comment out anything that follows, to avoid sql server rejecting or not committing the command because of syntax errors. Yes, Sql Server will run that additional statement, if that is what you put in a textbox.
So, your methods as written are broken, because the only accept completed sql strings as input. Any function that calls into the database MUST also include a mechanism for accepting query parameters. You ultimately want to be running code more like this:
Public Sub CreateReport(ByVal StartDate As DateTime, ByVal EndDate As DateTime)
Dim sql As String = _
"INSERT INTO tbl_report " & _
" (RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate) " & _
" SELECT StudID, Name, Course, Dept, LoginTime, LoginDate " & _
" FROM tblStudInfo " & _
" INNER JOIN tbl_studentLog ON tblStudInfo.StudID = tbl_studentLog.StudentNumber " & _
" WHERE tbl_studentLog.LoginDate BETWEEN #StartDate AND #EndDate"
'.Net is designed such in most cases that you really do want a new SqlConnection for each query
'I know it's counter-intuitive, but it is the right way to do this
Using cn As New SqlConnection("Connection string"), _
cmd As New SqlCommand(sql, cn)
'Putting your data into the query using parameters like this is safe from injection attacks
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = StartDate
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = EndDate
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
One thing to point out here is that at first glance I don't close the connection. However, the Using block will ensure that the connection is closed promptly... even if an exception is thrown. Your existing code will leave the connection hanging in the case of a exception.
Also note that this neatly side-steps the whole issue of needing to execute a separate query while your reader is opened... but if you ever do really need to do this (it's rare), the answer is simple: use a separate connection.
Instead of:
Dim SQLstatementSave As String = "INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
VALUES ('" & dr("StudID") & "','" & etc.
Try using .ToString on your DR() references.
Dim SQLstatementSave As String = "INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
VALUES ('" & dr("StudID").ToString & "','" & etc.