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.
Related
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???
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
i'm pretty new in VB.NET.
i'm trying to connect INTERBASE database (local) and get an error:
I've tried many things and nothing helped.
can't figure out what am I doing wrong or missed
Imports FirebirdSql
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim query As String = "select * from EMPLOYEE"
Dim csb As FbConnectionStringBuilder
Dim cnn As New FbConnection
csb = New FbConnectionStringBuilder()
csb.DataSource = "LOCALHOST"
csb.ServerType = 0
csb.Database = "c:\db\office.gdb"
csb.UserID = "SYSDBA"
csb.Password = "masterkey"
cnn = New FbConnection(csb.ToString)
Dim da As New FirebirdSql.Data.FirebirdClient.FbDataAdapter(query, cnn)
Dim ds As New DataSet
Dim dt As New DataTable
Try
cnn.Open()
da.Fill(dt)
cnn.Close()
cnn.Dispose()
Dim ans As String
If dt.Rows.Count > 0 Then
For Each row As DataRow In dt.Rows
ans = Convert.ToString(row.Item(1))
TextBox1.Text = ans
Next
Else
TextBox1.Text = "Record Not Found"
End If
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message, "Error")
End Try
End Sub
End Class
You cannot use FirebirdClient to connect to InterBase. Firebird and InterBase are not the same.
So...!!!
After digging the net I finally got it working!
Installed "Firebird_ODBC_2.0.3.154_Win32.exe" Downloaded from http://www.firebirdsql.org/en/odbc-driver/
fixed my script:
Dim query As String = "select * from EMPLOYEE"
Dim cnn As New Odbc.OdbcConnection()
Dim estring As New Odbc.OdbcConnectionStringBuilder("DRIVER=Firebird/InterBase(r) driver;UID=SYSDBA;PWD=masterkey;DBNAME=128.1.7.81:C:\office\db\office.gdb;")
cnn = New OdbcConnection(estring.ToString)
Dim da As New OdbcDataAdapter("select * from EMPLOYEE", estring.ToString)
Dim ds As New DataSet
Dim dt As New DataTable
Try
cnn.Open()
da.Fill(dt)
cnn.Close()
cnn.Dispose()
' (and so one).....
The connection established and I'm happy!
You were right about .NET OLE DB Provider for Firdbird (not working with Interbase), thank you all for the help.
I hope that this thread will help others with this problem.
I am doing a college assignment and have been trying to figure it out for hours, but I cant seem to get my new customer to save to the database! Please, I would really, REALLY apreciate it if you could have a look at my code, make any suggestions, or let me know more efficient ways of doing this. Bellow I provide a sample of my code for this.
To begin with, on form load I determine the new customer ID to be put into the database:
Private Sub frmRegister_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Me.CustomerTableAdapter.Fill(Me.DatabasePizzaPalaceDataSet.Customer)
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Year 2\Unit 17 Project Planning\Workto do\PizzaPalce\Program\DatabasePizzaPalace.accdb"
conn.Open()
Dim Rows As Integer
Dim sql As String = "SELECT * FROM Customer"
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
da = New OleDb.OleDbDataAdapter(sql, conn)
da.Fill(ds, "Customer")
Rows = ds.Tables("Customer").Rows.Count
NewCustomerID.Text = Rows + 1
Customer_IDTextBox.Text = NewCustomerID.Text
conn.Close()
End Sub
Now that being said, here is the piece of code I run when clicking on my save button for the recrod to be added through a new data row.
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Year 2\Unit 17 Project Planning\Workto do\PizzaPalce\Program\DatabasePizzaPalace.accdb"
conn.Open()
Dim inc As Integer
Dim sql As String = "SELECT * FROM Customer"
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
da = New OleDb.OleDbDataAdapter(sql, conn)
da.Fill(ds, "Customer")
inc = Customer_IDTextBox.Text
If inc <> -1 Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Customer").NewRow()
dsNewRow.Item("Customer_ID") = Customer_IDTextBox.Text
dsNewRow.Item("Username_Email") = Username_EmailTextBox.Text
dsNewRow.Item("Password") = PasswordTextBox.Text
dsNewRow.Item("First_Name") = First_NameTextBox.Text
dsNewRow.Item("Surname") = SurnameTextBox.Text
dsNewRow.Item("Mobile") = MobileTextBox.Text
dsNewRow.Item("House") = HouseTextBox.Text
ds.Tables("Customer").Rows.Add(dsNewRow)
da.Update(ds, "Customer")
MsgBox("New Record added to the Database")
conn.Close()
frmLogin.Show()
End If
'Dim cb As New OleDb.OleDbCommandBuilder(da)
'Me.CustomerTableAdapter.Insert(Customer_IDTextBox.Text, Username_EmailTextBox.Text, PasswordTextBox.Text, First_NameTextBox.Text, SurnameTextBox.Text, MobileTextBox.Text, HouseTextBox.Text)
'Me.CustomerTableAdapter.Fill(Me.DatabasePizzaPalaceDataSet.Customer)
'Me.Validate()
'Me.CustomerBindingSource.EndEdit()
'Me.CustomerTableAdapter.Fill(DatabasePizzaPalaceDataSet.Customer)
'Me.TableAdapterManager.UpdateAll(Me.DatabasePizzaPalaceDataSet)
'da.Update(ds, "Customer")
'MsgBox("You have been succesfully registerd with us. Thanks!")
'conn.Close()
'frmLogin.Show()
End Sub
In comments you can also see a code provided by my teacher, which we are supposed to improve, I just wish to find a way of making this work!
Thanks a lot, all help and suggestions are very appreciated.
Instead of ds.Tables("Customer") I used ds.Tables(0) (or whatever index your table is at inside your DataSet.)
Dim con As New OleDbConnection(_myConn) ''_myConn should be your connection string
con.Open()
Dim da As OleDbDataAdapter
Dim ds As New DataSet
da = New OleDbDataAdapter("select * from customer", con)
da.Fill(ds)
Dim cb As New OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables(0).NewRow()
dsNewRow.Item(1) = "1"
dsNewRow.Item(2) = "Blah"
dsNewRow.Item(3) = "Test"
dsNewRow.Item(4) = "T"
dsNewRow.Item(5) = "T"
dsNewRow.Item(6) = "T"
dsNewRow.Item(7) = "20000101"
ds.Tables(0).Rows.Add(dsNewRow)
da.Update(ds.Tables(0))
con.Close()
It's important to realize your database schema also. If your first column is an identity auto increment column, you want to avoid trying to insert anything to that column. I prefer to use the Indexes because it's a lot easier to misspell a column name as a string, although it may not be as clear.
So, Customer_ID may be (or not be) an auto-increment field, which means trying to insert data into that column will result in an error.
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.