Using VS 2017 and VB to connect to a database - vb.net

First of, I am a beginner.
more clarification:
I am writing this program in Vis. Basic to access a database, get values and save the info.
the database is a MS Access 2016 database.
I have multiple forms and on each form different values are entered.
I now made an ADD form to write all the data from all the forms in my database.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim sqlconn As New OleDb.OleDbConnection
Dim sqlquery As New OleDb.OleDbCommand
Dim connString As String
Dim custname, custnum, cgender, pkind, pmodel, probear, meduse, tint, tinl, crema, cneed As String
Dim byear As Integer
connString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\rolf\source\repos\AMEST_Audiology\AMEST_Audiology\bin\Debug\audiology.accdb"
sqlconn.ConnectionString = connString
sqlquery.Connection = sqlconn
sqlconn.Open()
sqlquery.CommandText = "INSERT INTO audiodat (custName,Custnum,cgender,pkind,pmodel,probear,meduse,tint,tinl,crema,cneed) Values (#custName,#custnum,#cgender,#pkind,#pmodel,#probear,#meduse,#tint,#tinl,#crema,#cneed)"
custname = FrmCust.custName
custnum = FrmCust.Custnum
cgender = FrmCust.CGender
byear = FrmCust.byear
pkind = FrmCust.pkind
pmodel = FrmCust.pmodel
probear = Frmhistory.probear
meduse = Frmhistory.meduse
tint = Frmhistory.tint
tinl = Frmhistory.tinl
crema = FrmClinic.crema
cneed = Frmsolution.cneed
sqlquery.Parameters.AddWithValue("#custname", custname)
sqlquery.Parameters.AddWithValue("#custnum", custnum)
sqlquery.Parameters.AddWithValue("#cgender", cgender)
sqlquery.Parameters.AddWithValue("#pkind", pkind)
sqlquery.Parameters.AddWithValue("#pmodel", pmodel)
sqlquery.Parameters.AddWithValue("#probear", probear)
sqlquery.Parameters.AddWithValue("#meduse", meduse)
sqlquery.Parameters.AddWithValue("#tint", tint)
sqlquery.Parameters.AddWithValue("#tinl", tinl)
' sqlquery.Parameters.AddWithValue("#oprobhis", oprobhis)
sqlquery.Parameters.AddWithValue("#crema", crema)
sqlquery.Parameters.AddWithValue("#cneed", cneed)
sqlquery.ExecuteNonQuery()
sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Frmprintdoc.Show()
Me.Close()
End Sub
it works as far as the String goes, but i cant save numbers or checkbox state.
it also does NOT actually write the data into the database, just into the memory of the tableadapter. what am i missing???

Related

Compare db value with textbox value VB

My Table
I load the windows user name to textbox1.text using 'System.Environment'
After that I query this and compare the textbox value to the PersonName in db
if it matches, I want to get the relevant Department name ie if it's 'manager'
then I want to display a form from menuitem_click event. My code is below
it dosent work can some one please help with this.
Private Sub MySamplesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles MySamplesToolStripMenuItem.Click
Dim cn As New SqlClient.SqlConnection("Data Source=ffff;Initial Catalog=ffff;User ID=****;Password=****;")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Dim ta As String
Try
cn.Open()
Dim sql As String
sql = "select * from dbo.Person where [PersonName] ='" + TextBox1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
ta = reader.Item("Department")
If ta = 'Maneger' Then
Form2.Show()
End If
' TextBox2.Text = reader.Item("Department")
'TextBox2.Text = reader.Item("dob")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
No matter how you spell it, Manager or Maneger, just make sure what is in the database matches what is in your If statement. I think I would use a drop down box for you to select the Department wherever you are inserting the Person so the Department name would match.
The Using...End Using blocks ensure that you database objects are closed and disposed even if there is an error.
You can pass your Sql statement and the connection directly to the constructor of the command. If all you need is the Department then don't drag down all the date with "*".
Never concatenate strings to build Sql statements. A hacker could type in TextBox1 "Joe; Drop Table dbo.Person;" Using parameters stops this hole because the .Value of the parameter is treated as only a value not executable code.
You are only expecting one value in return so you can use .ExecuteScalar which returns the first column of the first row in the result set.
Your code is very fragile because I suspect you could have duplicate names unless you require unique user names.
Private Sub MySamplesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles MySamplesToolStripMenuItem.Click
Try
Using cn As New SqlClient.SqlConnection("Data Source=ffff;Initial Catalog=ffff;User ID=****;Password=****;")
Using cmd As New SqlClient.SqlCommand("Select Department From dbo.Person Where PersonName = #Name;", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TextBox1.Text
cn.Open()
Dim ta As String = cmd.ExecuteScalar.ToString
If ta = "Maneger" Then
Form2.Show()
End If
TextBox2.Text = ta
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

VB.net Query wont retrieve data from access database

I have created a query using vb.net with parameters which should allow the query to retrieve data from my access database but however when I click on the button it only shows blank fields but no rows are retrieved from the database. Could you please help me what I am currently doing wrong.
Imports System.Data.OleDb
Public Class RouteToCruise
Private Sub RouteToCruise_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Route_Btn_Click(sender As Object, e As EventArgs) Handles Route_Btn.Click
Try
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT Route.RouteName + ', ' + Cruise.CruiseID As CruiseRoute FROM Route INNER JOIN Cruise ON Route.RouteID = Cruise.RouteID WHERE CruiseID = ?"
Dim cmd As New OleDbCommand(CruiseQuery, cn)
'cmd.Parameters.AddWithValue("CruiseID", OleDbType.Numeric).Value = Route_Txt.Text
cmd.Parameters.AddWithValue(("CruiseID"), OleDbType.Numeric)
Dim reader As OleDbDataReader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "RouteName"
While reader.Read
Dim rID As String = reader("RouteID").ToString()
cmd.Parameters.AddWithValue("?", rID)
row = reader("CruiseID") & "," & ("RouteName")
RCTable.Rows.Add(row)
End While
reader.Close()
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
If the user enters route name in the text box then the rows should show cruise ID and route name for each of the selected routes. for example if users enters Asia in the text box, clicks on the button then the query should return the cruiseID for the cruises which are going to Asia.
Your use of parameters makes no sense. First you call AddWithValue and provide no value, then you execute the query and then you start adding more parameters as you read the data. Either you call AddWithValue and provide a value, or you call Add and then set the Value on the parameter object created. Either way, it MUST be before you execute the query or it's useless.
myCommand.Parameters.AddWithValue("#ParameterName", parameterValue)
or
Dim myParameter = myCommand.Parameters.Add("#ParameterName", OleDbType.Numeric)
myParameter.Value = parameterValue

insert data during runtime

I have created students attendance management database. I have used sql server and VB12. My problem is I have created 2 datasets from my table. One dataset have register no and name. and other have register no, name,attendance ,total and percent. I successfully added reg no and name using first dataset.using second dataset i have to enter the attendance and find its total and percent for the newly created register no. when i enter the attendance and click my add button I receive a error msg tat + operator is not defined for db null.
I have two button connect and add. My code for buttons are,
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connetionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\ADMIN\Documents\Visual Studio 2012\Projects\studentattendance\studentattendance\attnd\details.mdf;Integrated Security=True"
connection = New SqlConnection(connetionString)
sql = "select * from entry"
Try
connection.Open()
adapter = New SqlDataAdapter(sql, connection)
adapter.Fill(ds)
connection.Close()
EntryDataGridView.DataSource = ds.Tables(0)
MsgBox("connected")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
connetionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\ADMIN\Documents\Visual Studio 2012\Projects\studentattendance\studentattendance\attnd\details.mdf;Integrated Security=True"
connection = New SqlConnection(connetionString)
sql = "select * from entry"
Try
connection.Open()
adapter = New SqlDataAdapter(sql, connection)
cmdBuilder = New SqlCommandBuilder(adapter)
adapter.Fill(ds)
For i = 0 To ds.Tables(0).Rows.Count - 1
ds.Tables(0).Rows(i).Item(9) = ds.Tables(0).Rows(i).Item(2) + ds.Tables(0).Rows(i).Item(3) + ds.Tables(0).Rows(i).Item(4) + ds.Tables(0).Rows(i).Item(5) + ds.Tables(0).Rows(i).Item(6) + ds.Tables(0).Rows(i).Item(7) + ds.Tables(0).Rows(i).Item(8)
ds.Tables(0).Rows(i).Item(10) = ds.Tables(0).Rows(i).Item(9) / 7
Next
adapter.Update(ds.Tables(0))
connection.Close()
MsgBox("Data updated ! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
please help me...
"+ operator is not defined for db null."
It's indeed not defined.
You need to check if the field contains a DBNull value.
IsDBNull(ds.Tables(n).Rows(n).Item(n))
For instance, if the 3'rd and 4'th column has the data type set to Integer:
Dim item2 As Object = ds.Tables(0).Rows(i).Item(2)
Dim item3 As Object = ds.Tables(0).Rows(i).Item(3)
Dim result As Integer = (
If(IsDBNull(item2), 0I, CInt(item2)) +
If(IsDBNull(item3), 0I, CInt(item3))
)
You should turn Option Strict ON ASAP as this will prevent you from doing this kind of mistakes in the future.

oledbCnn not connecting to Access Database

I'm trying to connect to a database. When I do a simple Select * it works, but the moment I add a WHERE clause it no longer properly works and says it cannot connect. The column name is correct, and I'm sure there is a last name of Lee in the database. Why would this work during a simple select and not when there is a where clause?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connetionString As String
Dim oledbCnn As OleDbConnection
Dim oledbAdapter As OleDbDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim i As Integer
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=S:\Reporting Database.mdb;"
sql = "SELECT * FROM [extract1] WHERE [extract1].[PI First Name] = Lee"
oledbCnn = New OleDbConnection(connetionString)
Try
oledbCnn.Open()
oledbAdapter = New OleDbDataAdapter(sql, oledbCnn)
oledbAdapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
oledbAdapter.Dispose()
oledbCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
I guess that you should put Lee between quotes, like:
sql = "SELECT * FROM [extract1] WHERE [extract1].[PI First Name] = 'Lee'"
Hint: use parameters to avoid sql injection.

Update a Single cell of a database table in VB.net

I am using MS Access Database. Now I have to update a particular cell value. Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim Presc As New System.Text.StringBuilder
Dim prs As String(), j As Integer
prs = Split(txtPrescription.Text, vbCrLf)
For j = 0 To prs.Length - 1
Presc.Append(prs(j))
Presc.Append(",")
Next
Try
str = Trim(lsvCase.SelectedItems(0).Text)
'MessageBox.Show(str)
Dim con As System.Data.OleDb.OleDbConnection
Dim ds As New DataSet
Dim rea As System.Data.OleDb.OleDbDataReader
con = New OleDb.OleDbConnection
Dim da As New System.Data.OleDb.OleDbDataAdapter
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source= F:\Sowmya Laptop Backups\sowdb1.accdb;"
con.Open()
Dim cmd As OleDb.OleDbCommand = con.CreateCommand
cmd.CommandText = "UPDATE Casehistory set Prescription =' " & Presc.ToString() & "'"
rea = cmd.ExecuteReader
cmd.ExecuteNonQuery()
da.FillSchema(ds, SchemaType.Mapped)
da.Update(ds, "Casehistory")
con.Close()
Catch ex As Exception
Finally
End Try
End Sub
This code updates all the cells in that column. I want to update only the particular cell having Case_ID = str
Where I have to add the WHERE clause (WHERE Case_ID = " & str & "
I would use command parameters, neater and prevents the SQL injection issue. Something like:
cmd.CommandText = "UPDATE Casehistory set Prescription =#Presc WHERE Case_ID = #CaseID"
cmd.Parameters.AddWithValue("#Presc", Presc.ToString())
cmd.Parameters.AddWithValue("#CaseID",str)
As an aside, having all this code in the button click event is less than ideal. You might want to investigate structuring your app in a more maintainable way - perhaps with a Data Layer for example.
The Where clause should be appended to the end of the OleDbCommmand.CommandText, where you define the Update statement.