Checking for result from MS Access database (VB.NET) - 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

Related

Delete record from SQL database in 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

"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.

SYNTAX ERROR INSERT INTO STATEMENT Visual Basic

Why am I getting this error
Syntax error INSERT INTO statement
Please help! Thanks in advance!
Dim cmd As New OleDb.OleDbCommand
If TabControl1.SelectedIndex = 0 Then
If Not cnn.State = ConnectionState.Open Then
'open connection if it is not yet open
cnn.Open()
End If
cmd.Connection = cnn
'check whether add new or update
If Me.txtStdID.Tag & "" = "" Then
'add new
'add data to table
cmd.CommandText = "INSERT INTO Student (StudentID, LastName, FirstName, MiddleInitial, Grade, Section, ContactNumber, AdviserID, CounselorID, ParentName)" & _
"VALUES('" & Me.txtStdID.Text & "','" & Me.txtLname.Text & "','" & _
Me.txtFname.Text & "','" & Me.txtMidInt.Text & "','" & _
Me.txtGrade.Text & "','" & Me.txtSection.Text & "','" & Me.txtContact.Text & "','" & _
Me.txtAdvID.Text & "','" & Me.txtConID.Text & "','" & Me.txtPname.Text & "')"
cmd.ExecuteNonQuery()
Well, this is a well known problem. Databases define many words as "reserved keywords", and if they are used for column names or table names, they need to be enclosed in the appropriate quoting character for your database.
Seeing that you are using an OleDbConnection I assume that you are using MS-Access as database. In that case the list of reserved keywords could be found here,
And indeed SECTION is a reserved keyword, so your query, should be written as
"INSERT INTO Student (......, [Section], ......
Said that, let's say something about string concatenation to build an SQL Query.
It's bad, bad, bad.... There are numerous problem with that. For example, what happens if one of your fields contains a single quote? The whole query will fail again with a Syntax error. Also, albeit more difficult to exploit with Access because it doesn't support multiple command texts there is the problem of SQL Injection to avoid at all costs. You need to learn how to use a PARAMETERIZED QUERY
Dim sqlText = "INSERT INTO Student (StudentID, LastName, FirstName, " & _
"MiddleInitial, Grade, [Section], ContactNumber, AdviserID, " & _
"CounselorID, ParentName) VALUES (?,?,?,?,?,?,?,?,?,?)"
If TabControl1.SelectedIndex = 0 Then
Using cnn = New OleDbConnection(...constring here....)
Using cmd = new OleDbCommand(sqlText, cnn)
cnn.Open()
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = Me.txtStdID.Text
cmd.Parameters.Add("#p2", OleDbType.VarWChar).Value = Me.txtLname.Text
.... and so on with the other parameters ....
.... strictly following the order of the fields in the insert....
cmd.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()

How to store checkboxlist all selected items into a database single column

My objective is to input all checked items from a checkbooxlist into a single column in my database.
I understand it is not a good design. However, this is the requirement.
Here is the code I use to get all the selected items from checkboxlist:
Dim listitems As String
listitems = ControlChars.CrLf
For i = 0 To (chkActivities.Items.Count - 1)
If chkActivities.GetItemChecked(i) = True Then
listitems = listitems & (i + 1).ToString & chkActivities.Items(i).ToString & ControlChars.CrLf
End If
Next
Here is the connection string and command executed to populate my table:
>
objCon.Open()
objCmd = New SqlCommand("insert into activity_by_customer (userID, city, personal_activities, BookingDate, price) values ( '" & frmLogin.userID & "','" & cbbCity.Text & "','" & listitems & "','" & Date.Today & "','" & lblpriceValue.Text & "' )", objCon)
objCmd.ExecuteNonQuery()
activitiesbycustomer.Update(Me.ResourcesDataSet.activity_by_customer)
MsgBox("Your booking has been successful")
objCon.Close()
However when I execute this code it crashes with an error. The error is as follows:
Incorrect syntax near 's'.
Unclosed quotation mark after the character string ' )'.
This error happens to appear because of 'listitems'.
Any help would be appreciated.
Not a problem in how you build your listitems, but in how you pass the values to the database.
Do not use string concatenation to build a sql command
objCon.Open()
objCmd = New SqlCommand("insert into activity_by_customer " & _
"(userID, city, personal_activities, BookingDate, price) " & _
"values (#usrID, #city, #itms, #dt, #price)", objCon)
objCmd.Parameters.AddWithValue("#usrID",frmLogin.userID)
objCmd.Parameters.AddWithValue("#city",cbbCity.Text)
objCmd.Parameters.AddWithValue("#itms", listitems)
objCmd.Parameters.AddWithValue("#dt",Date.Today)
objCmd.Parameters.AddWithValue("#price", lblpriceValue.Text)
objCmd.ExecuteNonQuery()
....
In this way, the framework code formats your values considering the presence of characters like a single quote and avoiding the consequent syntax error. Moreover, in this way you avoid Sql Injection attacks