Im trying to insert a data into database using vb - mysql

I am trying to add a new data in mySql database using vb . But the error always says [unit_type] is not allowed to be null . I even changed the column's setting in the main database . I disabled the not null checkbox .
Dim datetoday = Date.Today
Try
command = "INSERT INTO assets_table ([date_created], [unit_type]) VALUES ('" & datetoday & "' , '" & frm_viewAssets.lbl_fetch.Text & "')"
Dim cmd As MySqlCommand = New MySqlCommand(command, myconn.open())
cmd.Parameters.Add(New MySqlParameter("date_created", CType(datetoday, String)))
cmd.Parameters.Add(New MySqlParameter("unit_type", CType(frm_viewAssets.lbl_fetch.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconn.close()
Catch ex As Exception
myconn.close()
End Try

You did the right thing by trying to use parameters but you did it wrong. You added the parameters to the command but, instead of using parameter place-holders in your SQL, you still inserted the literal values. This:
command = "INSERT INTO assets_table ([date_created], [unit_type]) VALUES ('" & datetoday & "' , '" & frm_viewAssets.lbl_fetch.Text & "')"
should be this:
command = "INSERT INTO assets_table ([date_created], [unit_type]) VALUES (#date_created, #unit_type)"
and then I think that you will need to add the "#" prefix to the parameter names when you create them as well.

Keep the database objects local so you can be sure they are closed and disposed. Using...End Using blocks will handle that for you even if there is an error.
Don't open the connection until directly before the .Execute.
I assumed the type of date_created to be a Date.
It can improve the efficiency of your sql to include the datatypes of your parameters.
If all you are doing in your Try/Catch is closing the connection you are just swallowing errors.
Private Sub OPCode()
Dim datetoday = Date.Today
Dim Command = "INSERT INTO assets_table ([date_created], [unit_type]) VALUES (#date_created , #unit_type);"
Using myconn As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand(Command, myconn)
cmd.Parameters.Add("#date_created", MySqlDbType.Date).Value = datetoday
cmd.Parameters.Add("#unit_type", MySqlDbType.VarChar).Value = frm_viewAssets.lbl_fetch.Text
myconn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

Related

HOW TO USE UPDATE IN SQL WITH VB

Can you please help me, what the problem of my code:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
'UPDATE Data
openCon()
Try
cmd.Connection = con
cmd.CommandText = "UPDATE emp_table SET FNAME = '" & TextBox1.Text & "', LNAME= '" & TextBox2.Text & "', AGE = '" & TextBox3.Text & "', GENDER ='" & Gender & "', OFFICE STAFF= '" & ComboBox1.Text & "' Where ID ='" & TxtID.Text & "' "
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Suceessfully Updated Record")
TxtID.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
RBMale.Checked = False
RBFemale.Checked = False
ComboBox1.Text = ""
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
There are many problems in your code and if you look around this site I think you will find many partial answers that step by step will help you solve your problems. So I try to give you an answer where all the problems are examined, discussed and solved.
First problem: How do you handle the connection.
It seems that you have a global connection instance called con that you open with openCon. This is not a good approach and always a source of problems. You always need to check if the connection is closed properly or not. For example, in the code above you have forgot to close the connection in case of exception and this will lead to other exceptions in some code not related to this one. You keep resources on the server locked to you and this will decrease the performance of every one connection to that server.
I would change your openCon to this
Public Function openCon() as MySqlConnection
Dim con as MySqlConnection = new MySqlConnection(....here connection string ...)
con.Open()
return con
End Function
This will create a new instance of the MySqlConnection every time you call this method Now you can remove the global connection instance and use the one returned by openCon in this way
Using con As MySqlConnection = openCon()
.... code that use the local con object
End Using
This will close and destroy the connection even if an exception occurs inside the Using block and the ADO.NET libraries are smart enough to use a thing called Connection Pooling to reduce the time required to build and open a connection with the same connection string.
Second problem: The syntax error.
Looking at the point of the error suggested by the message I can see a field name composed by two words separated by a space. This is fine, but then you should remember that the sql parser cannot understand this and you need to help it enclosing the two words in a backtick character (ALT+096) so the parser understand that this is a single field name. Given the fact column names are an internal information of no concern for your end user then why use spaces in column names? If possible remove the space in column names.
Third problem: Sql Injection and other syntax errors
You are concatenating strings to build an sql command. But this is an easy target for wannabe hackers. Suppose that I write in your textBox1 this string instead of a First Name: Mario'; --
Then your command becomes
UPDATE emp_table SET FNAME = 'Mario'; -- xxxxxxxxxxxx
everything after -- is considered a comment and the query is still executable, but it changes every record in emp_table to have a first name equal to Mario.
But the query could fail as well if someone writes a Last Name that contains an apostrophe like O'Leary just now the query is no more syntactically valid.
The solution to this is always one. Use Parameters.
Recap of changes to your code.
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim cmdText as String = "UPDATE emp_table SET FNAME = #fname,
LNAME= #lname, AGE = #age, GENDER =#gender,
`OFFICE STAFF` = #staff
Where ID =#id"
Using con as MySqlConnection = openCon()
Using cmd as MySqlCommand = new MySqlCommand(cmdText, con)
Try
cmd.Parameters.Add("#fname", MySqlDbType.VarChar).Value = textBox1.Text
cmd.Parameters.Add("#lname", MySqlDbType.VarChar).Value = textBox2.Text
cmd.Parameters.Add("#age", MySqlDbType.VarChar).Value = textBox3.Text
cmd.Parameters.Add("#gender", MySqlDbType.VarChar).Value = gender
cmd.Parameters.Add("#staff", MySqlDbType.VarChar).Value = combobox1.Text
cmd.Parameters.Add("#id", MySqlDbType.VarChar).Value = txtID.Text
cmd.ExecuteNonQuery()
MsgBox("Suceessfully Updated Record")
TxtID.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
RBMale.Checked = False
RBFemale.Checked = False
ComboBox1.Text = ""
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
End Using
End Sub
In the recap I have added parameters for every single field that you want to update. But remember. Parameters should have a Type (The MySqlDbType here) that should match the type of the field and the value should be of the same type. For example it seems improbable that Age is a varchar field. So you should convert TextBox3.Text to an integer if the field is an integer.

inserting data on mysql using vb.net with VS2010

im trying to insert data in mysql but i just cant do it ive tried to search for answers on the net and tried everything on my code but it just wont insert here is the image of the error
hope some one can help me and thanks in advance ... MERRY CHRISTMAS !!
here is the code
myconn = New MySqlConnection
myconn.ConnectionString = "host=127.0.0.1;user=root;password=;database=engr_log"
Dim Reader As MySqlDataReader
Try
myconn.Open()
Dim query As String
query = "insert into log_tbl ('ID', 'owner_name', 'business_name', 'Amount_paid', 'Location', 'Date') values (NULL, '" & txtname.Text & "','" & txtbus.Text & "','" & txtamount.Text & "', '" & txtloc.Text & "','" & dtp1.Value & "');"
command = New MySqlCommand(query, myconn)
Reader = command.ExecuteReader
MessageBox.Show("Entry Saved!!","SAVE", MessageBoxButtons.OK, MessageBoxIcon.Information)
myconn.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
getlist()
End Sub
Remove the single quotes around the column in your insert statment:
insert into log_tbl (ID, owner_name, business_name, Amount_paid, Location, Date)...
But the bigger problem is you should use queries with parameters to not only avoid errors but also SQL injections.
Example:
Dim connectionString = "host=127.0.0.1;user=root;password=;database=engr_log"
Dim query = "insert into log_tbl (owner_name, business_name, Amount_paid, Location, Date) values (#owner_name, #business_name, #Amount_paid, #Location, #Date);"
Using connection As New MySqlConnection(connectionString)
Dim command As New MySqlCommand(query, connection)
command.Parameters.AddWithValue("#owner_name", txtname.Text)
command.Parameters.AddWithValue("#business_name", txtbus.Text)
command.Parameters.AddWithValue("#Amount_paid", txtamount.Text)
command.Parameters.AddWithValue("#Location", txtloc.Text)
command.Parameters.AddWithValue("#Date", dtp1.Text)
command.Connection.Open()
command.ExecuteNonQuery()
End Using
Even better, you can be explicit with the types:
command.Parameters.Add("#owner_name", SqlDbType.VarChar)
command.Parameters.Add("#business_name", SqlDbType.VarChar)
command.Parameters.Add("#Amount_paid", SqlDbType.Float)
command.Parameters.Add("#Location", SqlDbType.VarChar)
command.Parameters.Add("#Date", SqlDbType.DateTime)

Insert data to MySql and display in datagridveiw

Recently i developed a pos but i have an problem inserting the data and displaying the names of the table in datagrid view
here is some code :
Dim Query As String
Query = "insert into baza.artikli(barkod,naziv,kupovna,prodazna,kolicina,proizvoditel,opis) values ('" & TextBoxBarkod.Text & "','" & TextBoxNaziv.Text & "','" & kupovnacena & "','" & prodaznacena & "','" & kolicina & "','" & TextBoxProizvoditel.Text & "','" & TextBoxOpis.Text & "')"
COMMAND = New MySqlCommand(Query, konekcija)
READER = COMMAND.ExecuteReader
MessageBox.Show("Артиклот е успешно внесен !")
TextBoxBarkod.Text = ""
TextBoxKupovna.Text = ""
TextBoxNaziv.Text = ""
TextBoxOpis.Text = ""
TextBoxProdazna.Text = ""
TextBoxProizvoditel.Text = ""
TextBoxKolicina.Text = ""
konekcija.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
konekcija.Dispose()
And i tried:
Private Sub prikazitabela()
konecija = New MySqlConnection
konecija.ConnectionString =
"server=localhost;userid=root;password=root;database=bazaartikli123"
Dim SDA As New MySqlDataAdapter
Dim bazaDataSet As New DataTable
Dim bajndsors As New BindingSource
Try
konecija.Open()
Dim Query As String
Query = "select barkod as 'Баркод',naziv as 'Назив на артикал',kupovna as 'Куповна цена',prodazna as 'Продажна цена',opis as'Опис',ddv as 'ДДВ',makproizvod as 'Македонски прозивод' from bazaartikli123.artikli"
COMMAND = New MySqlCommand(Query, konecija)
SDA.SelectCommand = COMMAND
SDA.Fill(bazaDataSet)
bajndsors.DataSource = bazaDataSet
DataGridView1.DataSource = bajndsors
SDA.Update(bazaDataSet)
konecija.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
konecija.Dispose()
End Try
End Sub`
There are several things that can be improved, starting with using SQL parameters and executing your query:
Dim Query As String = <sql>
insert into baza.artikli
(barkod,naziv,kupovna,prodazna,kolicina,proizvoditel,opis)
values (#p1,#p2,#p3,#p4,#p5,#p6,#p7 )
</sql>.Value
Using dbcon As New MySqlConnection(MySQLConnStr)
Using cmd As New MySqlCommand(Query, dbcon)
' I dont really know what datatype these really are
cmd.Parameters.Add("#p1", MySqlDbType.VarChar).Value = TextBoxBarkod.Text
cmd.Parameters.Add("#p2", MySqlDbType.DateTime).Value = DTPNaziv.Value
cmd.Parameters.Add("#p3", MySqlDbType.Int32).Value = Convert.ToInt32(Textkupovna.Text)
' ...
dbcon.Open()
' this was missing:
cmd.ExecuteNonQuery()
End Using
dt = New DataTable
Using cmd As New OleDbCommand("SELECT * FROM baza.artikli")
dt.Load(cmd.ExecuteReader())
dgv2.DataSource = dt
End Using
End Using
I used an XML literal for the SQL mainly to avoid scrolling here, but it can make your code much more readable
There is little context for the code in the question, but connections ought be created as needed; DBCommand objects are highly query specific, so they too ought be created as needed rather than using global ones.
Use Using blocks to assure that DbConnections and other objects with a Dispose() method are properly disposed. The code closes, but does not Dispose of the connection.
Use SQL Parameters always. These assure the correct data type is passed, avoid the cruft of " Foo -'" & foovar & "' AND ..." in code, protect against special characters in strings as well as prevent SQL injection attacks.
Then cmd.ExecuteNonQuery() performs the insert.
After that, you can run a new query to get whatever data you want to display. Note that you do not need to create a DataAdapter to fill a table. It is not clear what you want to display, so that will also have to be modified for what you want.
When AutoGenerateColumns is True, they will be created when you set the datasource and the column names (== 'names of the table' ?) will automatically show. If you want different text to display for the headers, you can either set them manually or uses aliases for them in your SQL, as shown on a previous answer

cannot insert path file address to mysql using vb.net

i have problem to insert this text to mysql in vb.net
C:\Users\Riski\Documents\Visual Studio 2012\Projects\Remainder\Remainder\images\activ\
and this my source for insert
Try
Dim tbimg As String
tbimg = tbimgpath.text
'Prepare Connection and Query
dbconn = New MySqlConnection("Server=localhost;Database=team;Uid=root;Pwd=")
'OPEN THE DB AND KICKOFF THE QUERY
dbconn.Open()
DS = New DataSet
DA = New MySqlDataAdapter("INSERT INTO tb_team_user (id_team_user,user_ip,user_team,user_image_path) values (null,'" & lip.Text & "','" & tbteam.Text & "','" & tbimg & "')", dbconn)
DA.Fill(DS, "tb_info_activity")
'DONE CLOSE THE DB
dbconn.Close()
Application.Restart()
Catch ex As Exception
MsgBox("cannot connect to database!" & vbCrLf & vbCrLf & ex.Message)
End Try
if i write without symbol '\' and ':' the insert work fine but if i write with symbol and the insert give me warning just "check the manual that corresponds"
how resolve this?
thanks
Don't use string concatenation to build your sql query. Otherwise you are open for sql injection and other issues like this. The backslash introduces escape characters like \r for carriage return. So just use sql-parameters with the correct types:
Using dbconn = New MySqlConnection("connectionstring")
Dim insertSql = "INSERT INTO tb_team_user (id_team_user,user_ip,user_team,user_image_path)" & _
"VALUES (null,#user_ip,#user_team,#user_image_path)"
Using da As New MySqlDataAdapter()
da.InsertCommand = New MySqlCommand(insertSql, dbconn)
da.InsertCommand.Parameters.Add("#user_ip", MySqlDbType.Int32).Value = Int32.Parse(lip.Text)
da.InsertCommand.Parameters.Add("#user_team", MySqlDbType.VarChar).Value = tbteam.Text
da.InsertCommand.Parameters.Add("#user_image_path", MySqlDbType.VarChar).Value = tbimg.Text
' .. '
End Using
End Using
Apart from that, why do you use an INSERT-sql for DataAdaper.Fill? You need a Select.
So maybe you want to use MySqlCommand.ExecuteNonQuery instead:
Using dbconn = New MySqlConnection("connectionstring")
Dim insertSql = "INSERT INTO tb_team_user (id_team_user,user_ip,user_team,user_image_path)" & _
"VALUES (null,#user_ip,#user_team,#user_image_path)"
Using cmd As New MySqlCommand(insertSql, dbconn)
cmd.Parameters.Add("#user_ip", MySqlDbType.Int32).Value = Int32.Parse(lip.Text)
cmd.Parameters.Add("#user_team", MySqlDbType.VarChar).Value = tbteam.Text
cmd.Parameters.Add("#user_image_path", MySqlDbType.VarChar).Value = tbimg.Text
dbconn.Open()
Dim insertedCount As Int32 = cmd.ExecuteNonQuery()
End Using
End Using

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.