Delete record from SQL database in VB.NET - vb.net

I want to delete a record which is related to the SerialNo in the database.
This is my code:
Using con = New MySqlConnection("server=" & server & ";" & "user id=" & userid & ";" & "password=" & password & ";" & "database=" & database)
con.Open()
Dim sqlText = "DELETE * FROM datatable WHERE SerialNo = #ulogin"
Using cmd = New MySqlCommand(sqlText, con)
cmd.Parameters.AddWithValue("#ulogin", frmmain.txtinput.Text)
cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
This code doesn't work. When I run the program, the following error appears:
Please be kind enough to suggest a suitable solution.
NOTE: 221 means the entered number.

The * does not belong. You can't delete only specific columns from a record. You either delete the whole record or do nothing, and so there is no column list portion to a DELETE statement.
While I'm here, there's no need to call con.Close() (the Using block takes care of that for you) and it's better to avoid AddWithValue() in favor of an Add() overload that lets you be explicit about your parameter type.
Const sqlText As String = "DELETE FROM datatable WHERE SerialNo = #ulogin"
Using con As New MySqlConnection("server=" & server & ";" & "user id=" & userid & ";" & "password=" & password & ";" & "database=" & database), _
cmd AS New MySqlCommand(sqlText, con)
cmd.Parameters.Add("#ulogin", MySqlDbType.Int32).Value = frmmain.txtinput.Text
con.Open()
cmd.ExecuteNonQuery()
End Using

Related

VB.net Checking if database exists before connecting to it

I found the following query in order to find out if a database table was created already or not:
if db_id('thedbName') is not null
--code mine :)
print 'db exists'
else
print 'nope'
Now I am wanting to use that same query within my VB.net application. This is the code I currently have elsewhere that connects to the database (that I am wanting to see if its there before doing all this):
Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
"Initial Catalog=thedbName;" & _
"Integrated Security=True;" & _
"Pooling=False")
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"Print() 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"Print() 'nope'"
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Connection.Open()
Dim blah As String = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Of course the issue with this is that I have to know the database name first in order to connect to the database.
I then seem to be able to connect to the master database using this:
Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
"Integrated Security=True;" & _
"Pooling=False")
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"Print() 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"Print() 'nope'"
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Connection.Open()
Dim blah As String = cmd.ExecuteNonQuery()
cmd.Connection.Close()
But that query seems to throw an error on Dim blah As String = cmd.ExecuteNonQuery() of:
Additional information: Incorrect syntax near ')'.
So I'm not all sure what I am missing in order to correct the issue with the query?
Need to know how to have the query come back and say 'exists' or 'nope'
Change Print() to Print (remove the parentheses.)
Better, don't use Print at all, use select.
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"select 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"select 'nope'"
Dim blah As String = CType(cmd.ExecuteScalar(), string)
ExecuteNonQuery returns the number of affected rows for updates and inserts. But what you are executing is a query.
ExecuteScalar returns the first column of the first row selected. The query above only returns one row with one value, so that's what it will return.
or do it like this
select * from sys.databases where [name] = 'thedbName'
if it returns a row, then the database exists, if not then it doesn't.
To check if a table exists within a database, use this
select * from sys.objects where [name] = 'theTableName' and type_desc = 'USER_TABLE'

"variable" is not declared error

Image of the error
I am new to Vb.net programing and I need a little help here, I pretend to send info to my database, the first query gives me the id I need and I declare it as "postoid", when I later try to call it (in the insert into part) it says it is not declared, I have googled the problem a hundred times but I couldn't find the answer.
Ps: this code is all in the same private sub
Try
mysqlconn.Open()
queryrow = "Select * from postos where postos_nome ='" & TextBox1.Text & "'"
COMMANDuser1 = New MySqlCommand(queryrow, mysqlconn)
READERuser = COMMANDuser1.ExecuteReader
While READERuser.Read
Dim postoid = READERuser.GetString("postos_id")
End While
mysqlconn.Close()
Catch ex As Exception
End Try
Dim sqlquery As String = "INSERT INTO computadores VALUES (0,'" & pcname.ToUpper & "','" & ip & "','" & so & "','" & cpu & "','" & ram & "','" & gc & "','" & wserial & "','" & mnome & "','" & mserial & "','" & "--- ,,'Inativo','" & empresaid & "','" & postoid & "','" & userid & "')"
Dim sqlcommand As New MySqlCommand
With sqlcommand
.CommandText = sqlquery
.Connection = mysqlconn
.ExecuteNonQuery()
End With
MsgBox("Computador Adicionado")
Dispose()
Close()
Your variable postoid is out-of-scope outside the block it is declared in.
All you need to do is declare it outside the Try structure:
Dim postoid As String = ""
queryrow = "Select postos_id from postos where postos_nome = #PostosNome"
Using COMMANDuser1 As New MySqlCommand(queryrow, mysqlconn)
COMMANDuser1.Parameters.Add("#PostosNome", TextBox1.Text)
mysqlconn.Open()
READERuser = COMMANDuser1.ExecuteReader()
While READERuser.Read
postoid = READERuser.GetString("postos_id")
End While
mysqlconn.Close()
End Using
If postoid <> "" Then
' perform the insert...
I did not actually use Try in that, as you have no code in your Catch block - having no code in the Catch block has the effect of hiding errors. You want to see the errors.
For using SQL parameters, see, e.g., Inserting data into a MySQL table using VB.NET but please use .Add instead of .AddWithValue - the latter will not always work as intended.

Getting error while running the query [duplicate]

This question already has an answer here:
Why error ???? Syntax error in INSERT INTO statement
(1 answer)
Closed 7 years ago.
Here is my code.
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\speednet\speed_net.accdb")
Dim com As New OleDbCommand
con.Open()
com.Connection = con
com.CommandText = "insert into users (name,username,password,user_type) values ('" & name1.Text & "' ,'" & username.Text & "' ,'" & password.Text & "','" & account_type.Text & "')"
com.ExecuteNonQuery()
The error:
Syntax error in insert into statement ...
Cant find out the problem.
Password is a reserved keyword in access. You need square brackets around that word.
But your query should also be modified to use a parameter approach instead of string concatenation, otherwise more dangerous situation will be possible. Read about Sql Injection and what happen if one of your concatenated string contains a single quote.
So
Using con = New OleDbConnection("....")
Using com = New OleDbCommand("insert into users " & _
"(name,username,[password],user_type) " & _
"values (#name, #uname,#pass,#acctype)", con)
con.Open()
com.Parameters.AddWithValue("#name", name1.Text)
com.Parameters.AddWithValue("#uname", username.Text)
com.Parameters.AddWithValue("#pass", password.Text)
com.Parameters.AddWithValue("#acctype", account_type.Text)
com.ExecuteNonQuery()
End Using
End Using

execute multiple command for update vb.net

i am working on a vb project . in this i need to save some record to one table and update some records in another table in one event or click .. i am doing like this .
dim simpan as new sqlcommand
conn = New SqlConnection(connectionstring)
conn.Open()
simpan = New SqlCommand()
simpan.Connection = conn
simpan.CommandType = CommandType.Text
simpan.CommandText = "update barang set (nama_barang,harga)values(" & TextBox3.Text & ",'" & TextBox4.Text & "') where kode_barang = '" & TextBox2.Text & "'"
simpan.ExecuteNonQuery()
tampil()
MsgBox("Data Berhasil Diubah", MsgBoxStyle.Information, "Informasi")
conn.Close()
but it giving error as "incorrect syntax near '('" .. i am not getting where i go wrong .. please help me
I see a couple issues with this...
Your Syntax is wrong on your update statement (Al-3sli beat me to that one).
Your textbox values will cause issues if a user types a single quote in the text box (For Example: The word "Wasn't".
Add the replace function to each textbox TextBox3.text.Replace("'","''") That will replace single ticks with two single ticks.
You might also consider using parameterized queries
You can't use update like this, change your code like so:
simpan.CommandText = "update barang set nama_barang = '" & TextBox3.Text & "',harga ='" & TextBox4.Text & "' where kode_barang = '" & TextBox2.Text & "'"
simpan.ExecuteNonQuery()

Checking for result from MS Access database (VB.NET)

In my .NET application I have to manage bookings for rooms. I enter the room booking via an SQL query to a MS Access database using an INSERT INTO statement.
Before I insert the booking, I need to check if a booking already exists for that time period, and if it does stop the user from being able to book at that time.
I have written code to retrieve a database result on the day and time of the booking they want to book, and the fact that Access would return data would mean that the user is trying to book over someone else.
But I'm stuck on how I can check if I have a resuklt returned. My code:
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\Database\database.mdb;")
cn.Open()
cmd = New OleDbCommand("SELECT * FROM(" & roomvar.ToLower() & ") WHERE (((" & roomvar.ToLower() & ".date)=" & Chr(34) & dtpDate.Value.Date & Chr(34) & "))", cn)
dr = cmd.ExecuteReader
If dr.HasRows = True Then
MsgBox("There is an existing booking")
End If
dr.Close()
But this doesn't work, it displays the messagebox regardless of if there is a row returned or not. How can I check if a row was returned?
Thanks.
cmd = New OleDbCommand("SELECT Count(*) FROM(" & roomvar.ToLower() & ") WHERE (((" & roomvar.ToLower() & ".date)=" & Chr(34) & dtpDate.Value.Date & Chr(34) & "))", cn)
dim alreadyBooked as Integer = cmd.ExecuteScalar
If alreadyBooked > 0 Then
Msgbox "There is an existing booking"
End If
EDIT: vb.net is not the language I use. You might have to apply cast on cmd.ExecuteScalar.
Also, I would suggest the use of Using statement.
link: http://www.pluralsight.com/community/blogs/fritz/archive/2005/04/28/7834.aspx