vb.net, mysql inserting dates - mysql

hi im trying to insert dates from vb.net into my sql database and the results keep showing as 00-00-00 i use a date time picker to get the date which is formated to short
Public Sub NewAppointment()
SQLCommand.Connection = SQLconnection
SQLCommand.CommandText = "INSERT INTO " & _
appointment(TattooID,Date,Time,Length,Deposit,Cost) VALUES"& _
('" & _Tattoo.ID & "','"& _
" & AppDate.Date & "','" & _
" & AppTime & "','" & _
" & AppLength.ToString & "','" & _
" & AppDespoit & "','" & AppCost & "');"
SQLCommand.CommandType = CommandType.TableDirect
Try
SQLconnection.Open()
SQLCommand.ExecuteNonQuery()
SQLconnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
SQLconnection.Dispose()
End Sub

As usual these problems (and other as well) are totally avoided with a parameterized query
This is an example, you need to fix the correct datatype (MySqlDbType) for each parameter to match the datatype of your datatable fields
SQLCommand.Connection = SQLconnection
SQLCommand.CommandText = "INSERT INTO " & _
" appointment(TattooID,Date,Time,Length,Deposit,Cost) VALUES "& _
" (#id, #appDate, #AppTime, #AppLength,#AppDespoit,#AppCost);"
SQLCommand.Parameters.Add("#id", MySqlDbType.VarChar).Value = _Tattoo.ID
SQLCommand.Parameters.Add("#AppDate", MySqlDbType.Date).Value = AppDate.Date
SQLCommand.Parameters.Add("#AppTime", MySqlDbType.Date).Value = AppTime
SQLCommand.Parameters.Add("#AppLength", MySqlDbType.VarChar).Value = AppLength
SQLCommand.Parameters.Add("#AppDespoit", MySqlDbType.VarChar).Value = AppDespoit
SQLCommand.Parameters.Add("#AppCost", MySqlDbType.VarChar).Value = AppCost
Now, the job to get a correct value for your date field is passed to the database engine that receives a parameter of type Date and knows how to extract the value from the parameter and store it in the relative field.
Notice how your query is now more readable and, as an added benefit, you avoid any possible Sql Injection

Related

VB.NET Getting Duplicate in Inserting data in mysql

I'm trying to insert data in MYSQL and get the latest ID but the problem is I'm Inserting Duplicate data
Is my syntax is wrong or something?
connection.Open()
insertString = "INSERT INTO `daily_report`(`saan_nalaman`,`purpose`, `usual_time`, `apps`,`feedback`,`userid`, `survey_at_what_blh`) VALUES ('" & txtq1.Text & "', '" & txtq2.Text & "', '" & txtq3.Text & "', '" & txtq4.Text & "', '" & txtq5.Text & "', '" & Utilities.UserID & "', '" & Login.RichTextBox1.Text & "');SELECT last_insert_id();"
command = New MySqlCommand(insertString, connection)
reader = command.ExecuteReader
connection.Close()
connection.Open()
TextBox1.Text = command.ExecuteScalar
connection.Close()
Declare and dispose your database objects in the method where they are used. Using blocks handle this for us even if there is an error. Always use parameters to avoid sql injection. Also, it makes the sql command easier to read and write without all the concatenation and single quotes. A single ExecuteScalar will accomplish both the insert and the select.
Private ConStr As String = "Your connection string"
Private Sub GetID()
Dim insertString = "INSERT INTO `daily_report`(`saan_nalaman`,`purpose`, `usual_time`, `apps`,`feedback`,`userid`, `survey_at_what_blh`) VALUES (#saan, #purpose, #time, #apps, #feedback, #userid, #survey) SELECT last_insert_id();"
Dim id As Integer
Using Command As New MySqlCommand(insertString, New MySqlConnection(ConStr))
With Command.Parameters
.AddWithValue("#saan", txtq1.Text)
.AddWithValue("#purpose", txtq2.Text)
.AddWithValue("#time", txtq3.Text)
.AddWithValue("#apps", txtq4.Text)
.AddWithValue("#feedback", txtq5.Text)
.AddWithValue("#userid", Utilities.UserID)
.AddWithValue("#survey", Login.RichTextBox1.Text)
End With
Command.Connection.Open()
id = CInt(Command.ExecuteScalar)
End Using
TextBox1.Text = id.ToString
End Sub

Why do I get this kind of error "System.MissingMemberException: 'Public member 'Text' on type 'String' not found.'" in VB.Net

I'm trying to insert data to MySql using vb.net. When I try to insert I've got the error. Please Help me.
Private Sub addEmp_Click(sender As Object, e As EventArgs) Handles addEmp.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server=localhost;userid=root;password=;database=vbdb"
Dim READER As MySqlDataReader
Dim birthDate As String = bDay.Value.ToString("yyyy/mm/dd")
Dim dateHired As String = dHired.Value.ToString("yyyy/mm/dd")
Try
MysqlConn.Open()
Dim Query As String
Query = "insert into vbdb.employee_info (Last_Name, First_Name, Middle_Name, Gender, Birthdate, Address, Contact, Position, Emp_Type, Email, Date_Hired) values ('" & firstName.Text & "','" & lastName.Text & "','" & middleName.Text & "','" & gender.Text & "','" & birthDate & "','" & gender.Text & "','" & address.Text & "','" & contact.Text & "','" & position.SelectedItem.Text & "','" & type.SelectedItem.Text & "','" & email.Text & "','" & dateHired & "')"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = Command.ExecuteReader
MessageBox.Show("Data Saved")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
You're using position.SelectedItem.Text. Presumably position is a ComboBox or ListBox and you have bound it to some list. Presumably the property or column that you have specified via the ValueMember contains Strings. That means that position.SelectedItem is a String and you are trying to access a Text member that doesn't exist.
For one thing, you should turn Option Strict On. That code wouldn't even compile then. That would mean that, if position.SelectedItem is a String, you would have to cast it as that type, probably using CStr. If it wasn't already obvious that you already had the String you needed, the compiler would tell you without your having to run the project that type String had no Text property.

Current system datetime syntax in VB6.0 which is equivalent to sql datetime

brdSrNo = txt_Board_SrNo.Text
usrname = txt_User_Name.Text
ndate = Format$(Now, "yyyy-mm-dd hh:mm:ss")
voltMeas1 = txt_VoltMes.Text
rs.Open "insert into duct_test values(" & brdSrNo & ",'" & ndate & "'," & usrname & ", " & voltMeas1 & ")", con, adOpenDynamic, adLockBatchOptimistic
'here I get the error'
I tried the above code but the error appears as:Incorrect syntax near','. Is there anyway to get the datetime like this:2015-10-30 17:09:22.000, as we get in sql
thanks #nabuchodonossor & #Fred, I got the Datetime pblm fixed. Now I got another error.. where, if voltMeas1=12.5 r something that takes an voltage measure... the error shows : "Arithmetic overflow error converting numeric to datatype numeric" ,In the sql table VoltageMeasure data type is Numeric(2,2).. can u suggest anthying?
you can also use the server time:
instead of:
rs.Open "insert into duct_test values(" & brdSrNo & ",'" & ndate & "'," & usrname & ",
you can write:
rs.Open "insert into duct_test values(" & brdSrNo & ", GETDATE(), " & usrname & ",
and implement the changes of mentioned by Fred
I can see a couple of things wrong here
You are inserting a record so you do not need a recordset as you are not returning anything. Use cmd .Execute instead of rs.Open.
usrname is a string so needs to be wrapped in single quotes '
Your final code should like more like:
Private Sub cmd_update_Click()
Dim strSQL As String
Dim con As ADODB.Connection
Set con = New ADODB.Connection
con.ConnectionString = "Provider=SQLOLEDB;Data Source=SUVI.suvi.local;InitialCatalog=SUVI;Database=BLS;uid=sa;pwd=123458;"
con.Open
strSQL = "insert into duct_test values(" & brdSrNo & ", GetDate(),'" & usrname & "', " & voltMeas1 & ")"
con.Execute strSQL, , adCmdText
con.Close
Set con = Nothing
End Sub
As a side note it is advisable to replace single quotes in any data input by a user with double single quotes. For example:
usrname = Replace$(usrname, "'", "''")
This will help against SQL injection attacks. Im not saying it will total prevent this but it will help.
If the date you are inserting is always the current date and time you can, as
nabuchodonossor point out, use GetDate().

Inserting Data on mysql and vb.net

I've got a table name stocks with following Columns :
ItemID, Item, Serial, Quantity, Category, Class, Unit, Beg_Date
and this is what I coded on vb.net:
Private Sub Savebtn_Click(sender As Object, e As EventArgs) Handles Savebtn.Click
Try
If txtItemID.Text = "" Or txtItemName.Text = "" Or txtQuantity.Text = "" Or cBoxCategory.Text = "" Or cBoxClass.Text = "" Or cBoxUnit.Text = "" Or dtpAdd.Value =""Then
MsgBox("All fields required!")
Else
ConStr.Open()
Dim Add_Query As String
Add_Query = "INSERT INTO Stocks (ItemID,Item,Serial,Quantity,Category,Class,Unit,Beg_Date) VALUES ('" & txtItemID.Text & "','" & txtItemName.Text & "','" & txtSerial.Text & "','" & txtQuantity.Text & "','" & cBoxCategory.Text & "','" & cBoxClass.Text & "','" & cBoxUnit.Text & "','" & dtpAdd.Value & "')"
Cmd = New MySqlCommand(Add_Query, ConStr)
Rdr = Cmd.ExecuteReader
MsgBox("Successfully Added!")
Me.Hide()
ConStr.Close()
End If
Catch ex As MySqlException
MsgBox("Connection Failed!")
Finally
ConStr.Dispose()
End Try
End Sub
Everytime I save the data when user input values it always give me a
Mysqlexception error "Connection Failed!"..
Any Idea how to fix this?
Make sure you have closed all previous connections. Add the line
If(ConStr != ConnectionState.Open)
before opening the connection again
This will check for the connection being open before you try to open it again.
For the Catch, use
MsgBox("Connection Failed!" & Ex.Message)
to show the actual exception being thrown.
Also, unless you need to return records, using
Cmd.ExecuteNonQuery()
is preferred method to run an action query.

VB.net update query is not giving errors and not updating my sql database

Dim conntps As MySqlConnection
Dim myconnstringtps As String
conntps = New MySqlConnection()
Dim mycommand As New MySqlCommand
Dim Updatepayments As String = "update payments set payments.payorname='" & _
epayorname.Text & "', payments.cardnumber='" & eccnumber.Text & _
"', payments.bankname='" & ebankname.Text & "', payments.checkaccountnumber='" & _
eaccountnumber.Text & "', payments.checkroutingnumber='" & _
erouting.Text & "', payments.cardexpirationdate='" & eexpmonth.Text & "/" & _
eexpireyear.Text & "', payments.cardexpirationmonth='" & _
eexpmonth.Text & "', payments.cardexpirationyear='" & eexpireyear.Text & _
"', payments.cardaddress='" & eaddy.Text & "', payments.cardzipcode='" & _
ezip.Text & "', payments.threedigitnumber='" & ecvv.Text & _
"' where payments.filenumber='" & TextBox1.Text & "' and paymentstatus='PENDING';"
myconnstringtps = "server=localhost; user id=root; " & _
"password=1C0cac0la; database=collectionsmax"
Try
conntps.Open()
Try
mycommand.Connection = conntps
mycommand.CommandText = Updatepayments
mycommand.ExecuteNonQuery()
conntps.Close()
mycommand.Dispose()
Catch myerror As MySqlException
MsgBox("error connecting:" & myerror.Message)
End Try
Catch myerror As MySqlException
MsgBox("error connecting:" & myerror.Message)
Finally
If conntps.State <> ConnectionState.Closed Then conntps.Close()
MsgBox("Successfully Changed")
End Try
I am not getting any errors or exceptions when attempting to run the code.
I have tried to output the generated update query to a text box and running the code though mysql management studio, and it works perfectly. so im pretty sure its not an issue with the actual query being sent to the server.
I have used almost this exact same code to do insert into statements with no issues.
It is not updating the database when the code is ran through my VB.net application using the above outlined code.
You don't set the connection string in the MySqlConnection
myconnstringtps = "server=localhost; user id=root; password=1C0cac0la;......"
conntps = New MySqlConnection(myconnstringtps)
apart from that, you need to use parametrized query to avoid problems with single quotes inside your strings and the Sql Injection Attack security problem
Dim Updatepayments As String = "update payments " & _
"set payments.payorname=#name," & _
"payments.cardnumber=#cnum," & _
"payments.bankname=#bank," & _
"payments.checkaccountnumber=#actnum," & _
"payments.checkroutingnumber=#routing," & _
"payments.cardexpirationdate=#monthyear," & _
"payments.cardexpirationmonth=#month," & _
"payments.cardexpirationyear=#year," & _
"payments.cardaddress=#address," & _
"payments.cardzipcode=#zip," & _
"payments.threedigitnumber=#digits " & _
"where payments.filenumber=#file and paymentstatus='PENDING'"
Dim mycommand As New MySqlCommand(Updatepayments, conntps)
mycommand.Parameters.AddWithValue("#name", epayorname.Text)
mycommand.Parameters.AddWithValue("#cnum", eccnumber.Text)
mycommand.Parameters.AddWithValue("#bank", ebankname.Text)
mycommand.Parameters.AddWithValue("#actnum", eaccountnumber.Text);
mycommand.Parameters.AddWithValue("#routing", erouting.Text)
mycommand.Parameters.AddWithValue("#monthyear", eexpmonth.Text & "/" & eexpireyear.Text)
mycommand.Parameters.AddWithValue("#month", eexpmonth.Text)
mycommand.Parameters.AddWithValue("#year", eexpireyear.Text)
mycommand.Parameters.AddWithValue("#address", eaddy.Text)
mycommand.Parameters.AddWithValue("#zip", ezip.Text)
mycommand.Parameters.AddWithValue("#digits", ecvv.Text)
mycommand.Parameters.AddWithValue("#file", TextBox1.Text)
Other problematic point: Are you sure that your fields are all of string type? You pass for every field a string and surround the value with single quotes. This could fail if someone of your fields are not of string type. (these fields in particular could be not of string type payments.cardnumber, payments.checkaccountnumber, payments.cardexpirationmonth,payments.cardexpirationyear,payments.threedigitnumber)
Use command parameters. This makes it both safer (SQL injection) and easier to handle.
Dim Updatepayments As String = "UPDATE payments SET payments.payorname=#1, " & _
"payments.cardnumber=#2, ..." & _
"WHERE payments.filenumber=#11 AND paymentstatus='PENDING';"
mycommand.Parameters.AddWithValue("#1", epayorname.Text);
mycommand.Parameters.AddWithValue("#2", eccnumber.Text);
...
You can also use parameter names like #epayorname with SQL-Server but some connection types (like ODBC) only allow positional parameters.
Red alert You are obviously dealing with credit card information here and yet you are leaving yourself and your customers vulnerable to SQL injection attacks!
Also you have a password in your code that you posted on the public Internet!
(And Steve seems to have the right answer.)