Get result of MS Access query into textbox in VB.NET - vb.net

I have a table in MS Access which has a colum named NameC (using ODBC to connect to MS Access)
I want the result of the following query to be saved in a txtField
Dim query = "SELECT NameC FROM Table WHERE ClientID = " & Integer.Parse(clientID)
How to do that in VB.NET?
I have a txtNameC.Text field
I currently was reviewing some sample code and they do:
Dim _consultationTable As DataTable
Public Sub Load()
Dim query = "SELECT * FROM Table WHERE ClientID = " & Integer.Parse(clientID)
Me._consultationTable = DatabaseFunctions.GetDataTable(query)
dvgInfo.Rows.Clear()
For Each dtRow In Me._consultationTable.Rows
dvgInfo.Rows.Add()
dvgInfo.Rows.Add(dvgInfo.RowCount-1).Cells("ColClientID").Value = dtRow("ClientId").ToString()
Next
but I do not want to fill a table I just want to get the result of a query into a text box
How can I do this?
I want to do something like this but just return a value and save it into a textbox
Protected Sub BindData()
strSQL = "SELECT * FROM customer"
Dim dtReader As OdbcDataReader
objCmd = New OdbcCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
'*** BindData to GridView ***'
myGridView.DataSource = dtReader
myGridView.DataBind()
dtReader.Close()
dtReader = Nothing
End Sub
Protected Sub BindData()
strSQL = "SELECT SpecificValue FROM customer where x = y..."
Dim dtReader As OdbcDataReader
objCmd = New OdbcCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
'*** BindData to GridView ***'
myGridView.DataSource = dtReader
myGridView.DataBind()
dtReader.Close()
dtReader = Nothing
End Sub

use DataReader.populate ur data from database in the datareader & from the the datareader u can use perticular values.
i don't know your code,that's why i m giving one simple example.
here is one example.
imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim oledbCnn As OleDbConnection
Dim oledbCmd As OleDbCommand
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
sql = "Your SQL Statement Here like Select * from product"
oledbCnn = New OleDbConnection(connetionString)
Try
oledbCnn.Open()
oledbCmd = New OleDbCommand(sql, oledbCnn)
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
While oledbReader.Read
MsgBox(oledbReader.Item(0) & " - " & oledbReader.Item(1) & " - " & oledbReader.Item(2))
End While
oledbReader.Close()
oledbCmd.Dispose()
oledbCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

Related

Database locked in vb.net when trying to update data in vb.net

Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

How to create a query in Visual Studio 2013 using Visual Basic

I have the following code and through debugging the problem begins at the While loop. I am trying to retrieve information from 2 tables and insert it into the table created. The information is not being inserted into the table and I am getting blank rows.
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
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=M:\ICT-Group-Project\DeepBlueProject\DeepBlueProject\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT CruiseID, RouteID FROM Cruise WHERE CruiseID =?"
Dim RouteQuery As String = "SELECT RouteName FROM Route WHERE RouteID =?"
Dim cmd As OleDbCommand = New OleDbCommand(CruiseQuery, cn)
Dim cmd2 As OleDbCommand = New OleDbCommand(RouteQuery, cn)
cmd.Parameters.AddWithValue("?", Route_Txt.Text)
Dim reader As OleDbDataReader
reader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "Route"
While reader.Read()
Dim rID As String = reader("RouteID").ToString()
cmd2.Parameters.AddWithValue("?", rID)
Dim reader2 As OleDbDataReader = cmd2.ExecuteReader()
'MsgBox(reader.GetValue(0) & "," & reader.GetValue(1))
row = reader("CruiseID") & "," & reader2("RouteName")
RCTable.Rows.Add(row)
cmd.ExecuteNonQuery()
reader2.Close()
End While
reader.Close()
cn.Close()
End Sub
End Class
If I understand your tables structure well then you could just run a single query extracting data from the two table and joining them in a new table returned by the query
Dim sql = "SELECT c.CruiseID c.CruiseID & ',' & r.RouteName as Route " & _
"FROM Cruise c INNER JOIN Route r ON c.RouteID = c.RouteID " & _
" WHERE c.CruiseID = #cruiseID"
Dim cmd As OleDbCommand = New OleDbCommand(sql, cn)
cmd.Parameters.Add("#cruiseID", OleDbType.Int).Value = Convert.ToInt32(Route_Txt.Text)
Dim RCTable = new DataTable()
Dim reader = cmd.ExecuteReader()
reader.Load(RCTable)
At this point the RCTable is filled with the data coming from the two tables and selected using the Route_Txt textbox converted to an integer. If the CruiseID field is not a numeric field then you should create the parameter as of type OleDbType.VarWChar and remove the conversion to integer
Try simplifying your query.
Dim CruiseRouteQuery As String = "SELECT C.CruiseID, C.RoutID, R.Routename FROM Cruise C LEFT JOIN Route R ON C.RouteID = R.RoutID WHERE CruiseID =?"
Also, please let us know what errors you are getting.

vb.net cannot write Query to MSAccess file

i can access to local Access Database and i can add some data using Query, but it JUST shows its data when the program is alive. when I re-execute this program, i cannot see any previously added data and so do original Database file(SourceDB.mdb).
How can I save my data? Here is my code.
Imports System.Data.OleDb
Public Class UserForm
Private myConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=.\SourceDB.mdb"
Private mDbConn As OleDbConnection
Private Sub Button_Search_Click(sender As Object, e As EventArgs) Handles Button_Search.Click
Dim myAdapter As New OleDbDataAdapter("SELECT * FROM user WHERE u_name = '" + tBoxName.Text + "'", myConn)
Dim myDataTable As New DataTable
If tBoxName.Text = "" Then
MsgBox("Input name")
Else
myAdapter.Fill(myDataTable)
If myDataTable.Rows.Count > 0 Then
tBoxPhone.Text = myDataTable.Rows(0).Item("u_phone")
tBoxAddr.Text = myDataTable.Rows(0).Item("u_addr")
tBoxBName.Text = myDataTable.Rows(0).Item("u_bname")
tBoxBAccount.Text = myDataTable.Rows(0).Item("u_baccount")
tBoxEtc.Text = myDataTable.Rows(0).Item("u_comment")
Else
MsgBox("No Name in Table")
End If
End If
End Sub
Private Sub Button_OK_Click(sender As Object, e As EventArgs) Handles Button_OK.Click
Try
If lblAOE.Text = "Add" Then
Dim myAdapter As New OleDbDataAdapter("INSERT INTO user (u_name, u_phone, u_addr, u_bname, u_baccount, u_comment) VALUES ('" + _
tBoxName.Text + "', '" + tBoxPhone.Text + "', '" + tBoxAddr.Text + "', '" + tBoxBName.Text + _
"', '" + tBoxBAccount.Text + "', '" + tBoxEtc.Text + "')", myConn)
Dim myDataTable As New DataTable
myAdapter.Fill(myDataTable)
Button_Add.Visible = True
Button_Modify.Visible = True
Button_OK.Visible = False
ClearTextBoxes()
Button_Clear.Text = "비우기"
End If Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button_Delete_Click(sender As Object, e As EventArgs) Handles Button_Delete.Click
If MessageBox.Show("Sure Wanna delete data?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Cancelled")
Exit Sub
Else
Dim myAdapter As New OleDbDataAdapter("DELETE FROM user WHERE u_name = '" + tBoxName.Text + "'", myConn)
Dim myDataTable As New DataTable
myAdapter.Fill(myDataTable)
MsgBox("DELETED")
ClearTextBoxes()
End If
End Sub
Private Sub ClientForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.UserTableAdapter.Fill(Me.SourceDBDataSet.user)
Me.Text = "User Form"
End Sub
End Class
You are using a OleDbDataAdapter trying to execute an INSERT operation (or a DELETE one), but this is not how the OleDbDataAdapter works.
An OleDbDataAdapter uses the SELECT command to retrieve the records and, if defined, its InsertCommand property to update records of a dataset through the call to the OleDbDataAdapter.Update method. You are not in this situation and you have your values directly in the textboxes. You could simply use an OleDbCommand with the appropriate sql statement (and this is the same for your DELETE method)
Try to change your code to
Dim cmdText = "INSERT INTO [user] (u_name, u_phone, u_addr, u_bname, " & _
"u_baccount, u_comment) VALUES (?, ?, ?, ?,?,?)"
Dim cmd = New OleDbCommand(cmdText, myConn)
cmd.Parameters.AddWithValue("#p1",tBoxName.Text)
cmd.Parameters.AddWithValue("#p2",tBoxPhone.Text )
cmd.Parameters.AddWithValue("#p3",tBoxAddr.Text)
cmd.Parameters.AddWithValue("#p4",tBoxBName.Text)
cmd.Parameters.AddWithValue("#p5",tBoxBAccount.Text)
cmd.Parameters.AddWithValue("#p6",tBoxEtc.Text )
cms.ExecuteNonQuery()
I have changed your string concatenation to a more correct parameterized query to avoid Sql Injection and parsing problems in case one of your textbox values contains a single quote.
you use OleDbCommand class. you make class object and use ExecuteNonQuery for insert data
like
Dim o As OleDbCommand
o.Connection = con
o.CommandType = CommandType.Text
o.CommandText = "your Query"
o.ExecuteNonQuery()
and you should use try block
try
o.ExecuteNonQuery()
catch
end try

Can't retrieve data with dot symbol from sql database

In my project (vb.net) I store the ip address of a website in a table with column of type nvarchar. But I can't retrieve it from the table. I wonder if its a problem with "dot" symbol. Please help.
This is the command that I use
query = "select *from restricted_sites where site_address='" + webip + "'"
webip is the ip address of web site.
Imports System.Data.SqlClient
Imports System.Net
Public Class restrict
Private Sub clear_button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clear_button.Click
site_TextBox1.Text = ""
addr_TextBox1.Text = ""
End Sub
Private Sub submit_button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submit_button.Click
Dim connectionstr As String
Dim query As String
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim webip As String
Dim hostname As IPHostEntry = Dns.GetHostByName(addr_TextBox1.Text)
Dim ip As IPAddress() = hostname.AddressList
Try
webip = ip(0).ToString
connectionstr = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\URLTrack.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
conn = New SqlConnection(connectionstr)
conn.Open()
query = "insert into restricted_sites values('" + site_TextBox1.Text + "','" + webip + "')"
cmd = New SqlCommand(query, conn)
cmd.ExecuteNonQuery()
MsgBox("Website added for restriction", MsgBoxStyle.Information)
conn.Close()
Catch ex As SqlException
End Try
End Sub
End Class
Private Sub Combox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Combox1.KeyPress
If e.KeyChar = Convert.ToChar(Keys.Enter) Then
Dim connectionstr As String
Dim query As String
Dim cmd As SqlCommand
Dim reader As SqlDataReader
Dim conn As SqlConnection
Dim url As String = ""
Dim webip As String
Dim hostname As IPHostEntry = Dns.GetHostByName(Combox1.Text)
Dim ip As IPAddress() = hostname.AddressList
webip = ip(0).ToString
connectionstr = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\URLTrack.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
conn = New SqlConnection(connectionstr)
conn.Open()
query = "select * from restricted_sites where site_address='" + webip + "'"
cmd = New SqlCommand(query, conn)
reader = cmd.ExecuteReader
While (reader.Read())
url = reader(2)
End While
reader.Close()
MsgBox(url, MsgBoxStyle.Information)
If webip <> url Then
AxWebBrowser1.Navigate(Combox1.Text)
Combox1.Text = AxWebBrowser1.LocationURL
Else
MsgBox("This Web Page is Restricted.Contact the ADMIN for Further Info", MsgBoxStyle.Critical)
End If
End If
If e.KeyChar = Convert.ToChar(Keys.Escape) Then
AxWebBrowser1.Stop()
End If
End Sub
The second code is the comparing part.
query = "select * from restricted_sites where site_address='" + webip + "'"
this code is the problem.
This is my code for restricting web sites through matching with ip address stored in database,when the url is being navigated.
You have a syntax error on your query. you forgot the space between * and from.
select *from restricted_sites
^ here
it should be
select * from restricted_sites
side note, since you are using VBNet, please do parameterized your query by using adonet command and parameters as your current query is susceptible with SQL Injection.
You need to put a space between the * and the from like so:
query = "select * from restricted_sites where site_address='" + webip + "'"
Dot symbols (presumably you meant in the webip) won't be a problem because it is in a String
If all you are doing is checking if an IP address string is in the database, you only need to count the number of occurences of that string:
query = "SELECT COUNT(*) FROM restricted_sites WHERE site_address = #WebIp;"
cmd = New SqlCommand(query, conn)
' assumes the ip address column is 15 chars '
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#WebIp", _
.SqlDbType = SqlDbType.NVarChar, _
.Size = 15, _
.Value = webip})
conn.Open()
Dim nFound = CInt(cmd.ExecuteScalar)
conn.Close()
If nFound = 0 Then
' site is not in restricted list
End If
Also, you should not use SELECT * in code other than for testing - use the column names instead of * and only retrieve what you need.

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.