getting variables into sql string from list box - sql

I am having a problem trying to get the contents of a list box into and SQL string via a variable(moon)
Here are 3 SELECT strings from the main body of code below.The last two strings work fine
but the first one doesn't.That's the one where I try and place the variable into the code
I have tried a few variations on the code but nothing seems to work.Does anybody have any suggestions.
THE SQL STRINGS:
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon "' ", myConnection) 'fails
da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works{
MAIN CODE BODY
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.Odbc
Imports System.Data.DataTable
Public Class Form1
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim ds As DataSet = New DataSet
Dim da As OleDbDataAdapter
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim moon As String
moon = ListBox1.Text
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Documents and Settings\james\Desktop\Authors.accdb" ' change to access database location on your computer
connString = provider & dataFile
myConnection.ConnectionString = connString
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon & "' ", myConnection) 'fails
'da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
'da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works
da.Fill(ds, "books")
' replace "items" with the name of the table
' replace [Item Code], [Description], [Price] with the columns headers
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
End Sub
End Class

Best practice is to use a new connection object for each call to the database, define objects with the smallest scope possible, and to use parameterized queries instead of substituting the value into your sql string.
Under no circumstances should you ever use string manipulation to put a user-selected value into your sql statement! Code like this is very bad:
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon & "' ", myConnection)
Imagine what would happen in this example if you have an author like "Patrick O'Neil". There are many ways this problem can be further abused to cause real damage to your database, application, and users. Just don't use string concatenation for this.
Do it like this instead:
Public Class Form1
Private Const provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Private Const dataFile As String = "C:\Documents and Settings\james\Desktop\Authors.accdb" ' change to access database location on your computer
Private connString As String = provider & dataFile
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ds As New DataSet()
'Set a special placeholder for your value as part of a *constant* sql statement
Dim sql As String = "SELECT * FROM books WHERE [author] = ? "
Using cn As New OleDbConnection(connString), _
cmd As New OleDbCommand(sql, cn), _
da As New OleDbDataAdapter(cmd)
'Set the value for that placeholder via a query parameter
'Parameters work best when you set the actual type and length
' to match your database. I had to guess at the length here.
cmd.Parameters.Add("?", OleDbType.NVarChar, 50).Value = Listbox1.Text
da.Fill(ds, "books")
End Using
DataGridView1.DataSource = ds.Tables("books")
DataGridView1.Refresh()
End Sub
End Class

Related

Retrieving data between two dates from Access database using VB.NET

I want to display data from a database in a datagridview. I am getting error on da.Fill(ds, "SAMPLE") with "data type mismatch error". Please see screenshot.
My date formats are 'short date' both datetimepicker and database values.
Imports System.Data.OleDb
Public Class Form1
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Recto D Sanchez Jr\Documents\sample.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from SAMPLE where [LOGDATE] between '" & DateTimePicker1.Text & "' And '" & DateTimePicker2.Text & "'", MyConn)
da.Fill(ds, "SAMPLE")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
End Sub
End Class
error screenshot
Since your DateTimePicker controls already deal with proper DateTime values you might have better luck using a parameterized query like this:
MyConn = New OleDbConnection(connString)
Dim cmd As New OleDbCommand("SELECT * FROM [SAMPLE] WHERE [LOGDATE] Between ? And ?", MyConn)
cmd.Parameters.AddWithValue("?", DateTimePicker1.Value.Date)
cmd.Parameters.AddWithValue("?", DateTimePicker2.Value.Date)
da = New OleDbDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "SAMPLE")
It would save you the trouble of dealing with different date formats, delimiting date literals, and other potential pitfalls.
Try
da = New OleDbDataAdapter("Select * from SAMPLE where [LOGDATE] between #" & DateTimePicker1.Value.ToString("MM/dd/yyyy HH:mm:ss") & "# And #" & DateTimePicker2.Value.ToString("MM/dd/yyyy HH:mm:ss") & "#", MyConn)

check values of column in sql

I am trying to collect values from a database, and if they are X value sett he background colour to green.
Basically, I have a Rota system, and if the user is working, then change the background colour. The select * will only bring back 1 row ever.
Imports System.Data.SqlClient
Imports System.Data.OleDb
Public Class Form4
Dim Con As SqlConnection
Dim cmd As New OleDbCommand
Dim sqlstring As String
Dim connstring As String
Dim ds As DataSet
Dim da As SqlDataAdapter
Private Sub Form4_Load(sender As Object, e As EventArgs)
connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Assignment.mdf;Integrated Security=True;Connect Timeout=30"
Con = New SqlConnection(connstring)
Con.Open()
Dim strSQL As String = "SELECT * from Users"
Dim da As New SqlDataAdapter(strSQL, Con)
Dim ds As New DataSet
da.Fill(ds, "Users")
With cboname
.DataSource = ds.Tables("Users")
.DisplayMember = "Name"
.ValueMember = "Id"
.SelectedIndex = 0
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Con As SqlConnection
Dim cmd As New OleDbCommand
Dim sqlstring As String
Dim connstring As String
Dim ds As DataSet
Dim da As SqlDataAdapter
connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Assignment.mdf;Integrated Security=True;Connect Timeout=30"
Con = New SqlConnection(connstring)
Con.Open()
sqlstring = ("SELECT * FROM Rota WHERE UserId ='" & cboname.SelectedIndex & "' and ID ='" & dtp1.Value & "'")
da = New SqlDataAdapter(sqlstring, Con)
ds = New DataSet
da.Fill(ds, "Rota")
End Sub
End Class
After this, I understand I need to get a few IF statements, but I am unsure on how to construct them.
To check a value in a DataSet use first get a DataTable inside of it, then a DataRow, then check one of the field values:
ds.Tables(0).Rows(0)("{field name}");
So to change the color based on some value:
If ds.Tables(0).Rows(0)("{field name}") = "Red" Then
textbox1.BackColor = Color.Red
End If
Some other comments:
A DataSet may be a bit heavy for getting one value (unless you're binding to a control). You can just use ADO.NET objects and use ExecuteScalar)
It's safer to use parameters instead of concatenating SQL statements (prevents SQL Injection and errors from special characters)
You can refactor your code to put the connection string in a single location rather than duplicating it across methods.

VB SQL ACCESS Select Where Like Statement

Net, i'm trying to learn how to display a query result into data grid whenever i click the Search Button as a trigger event for the query.
But nothing happens when i click the Search Button but gives me an error message (Please see link for the screenshot of error message) which i don't understand.
Error: http://s1.postimg.org/di091riv3/error1.jpg
Can you please point me to the right track, Thanks.
Here is my code below
Imports System.Data.OleDb
Public Class SearchForm
Dim con As New OleDbConnection
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Statd.SelectedIndexChanged
End Sub
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
con.Open()
Dim sqlQuery As String
Dim sqlCommand As New OleDbCommand
Dim sqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim empNum As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
empNum = eNumText.Text
empLname = empLnameText.Text
empDept = Deptd.Text
empStat = Statd.Text
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '% " & empLnameText.Text & "' "
' MsgBox("Employee Number " + empNum + empLname + empDept + empStat) 'test statement
With sqlCommand
.CommandText = sqlQuery
.Connection = con
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
For i = 0 To Table.Rows.Count - 1
With DataGridView1
.Rows.Add(Table.Rows(i)("EmpID"), Table.Rows(i)("FirstName"), Table.Rows(i)("LastName"), Table.Rows(i)("Department"), Table.Rows(i)("Position"), Table.Rows(i)("Status"), Table.Rows(i)("Years"))
End With
Next
End With
con.Close()
End Sub
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '%' + ? + '%' "
'It's counter-intuitive, but it's best in .Net to use a new connection object each time
Using con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"), _
cmd As New OleDbCommand(sqlQuery, con)
'Use actual column type and length here
cmd.Parameters.Add("?", OleDbType.NVarChar, 50).Value = empLnameText.Text
con.Open()
DataGridView1.DataSource = cmd.ExecuteReader()
End Using
End Sub
Try to change the % to * in your query, just like this:
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '* " & empLnameText.Text & "' "
Access doesn't use % as wildcard:
http://www.techonthenet.com/access/queries/like.php
I spotted an error in the usage of %. It is used for SQL Server and Not Access SQL use * in place of %

Insert a record in sql database using vb.net datatable and datarow features

I am trying to insert a record in sql database using vb.net dataadapter, datatable, and datarow features. I use the following code but it gives me an error:
Object reference not set to an instance of an object
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=drpractice;Integrated Security=True")
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Try
cn.Open()
da.SelectCommand = New SqlCommand("SELECT * FROM [emp_tbl]", cn)
da.Fill(ds)
Dim dt As New DataTable
dt = ds.Tables("emp_tbl")
'Error in this line(Object reference not set to an instance of an object)'
Dim dr As DataRow = dt.NewRow()
dr.Item("emp_id") = TextBox1.Text.Trim
dr.Item("emp_name") = TextBox2.Text.Trim
dr.Item("salary") = TextBox3.Text.Trim
dr.Item("age") = TextBox4.Text.Trim
dr.Item("emp_group") = TextBox5.Text.Trim
dt.Rows.Add(dr)
da.Update(ds)
MsgBox("Record Successfully Inserted")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
check this out : Dim dr As DataRow = new dt.NewRow()
You have done everything good but change the following line:
da.Update(ds)
As following:
Dim ESCBuilder As SqlCommandBuilder = New SqlCommandBuilder(da)
ESCBuilder.GetUpdateCommand()
da.UpdateCommand = ESCBuilder.GetUpdateCommand()
da.Update(ds)
Based on the feedback here and elsewhere, the following code worked for me:
TestDataSet.GetChanges()
testTableAdapter.Fill(TestDataSet.log_test)
log_testDataGridView.Refresh()
What I needed to do was, create a new row, and go get the next value for the Primary Key(VARCHAR, NOT INT, because revisions got an "R" appended to the PK...not my rule...the rule of the company).
I wanted to put the refresh as close to the getting of the PK, which I had last after assigning values to the new datarow so it would get the latest Max +1.
So, I put the above code just before looking up the PK, and after assigning values to the datarow, other than PK. The code above caused the datarow to blank out. So, I put the above code just prior to the creation of the new DataRow.
For my code, this caused the code to get the latest data from the SQL table, then add the new datarow, and finally determine the last PK. Because the data used to populate the datarow is off my form, and there is no caclulations, the code runs fast enough for my needs. I suspect, if the connection to my database was slow, and/or, the number of people running the same process were substantial, I would have errors, such as duplicate PKs.
My answer to that would be to assign the datarow field values to variables, run the refresh, then assign the variables to the fields and save immediately.
Perhaps another way would be to get the new PK, then save an empty record, and then fill the record, except that enough of the fields in my table are REQUIRED so I might as well not try creating a blank record first.
Imports System.Data.SqlClient
Public Class Form4
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim str As String
Dim count As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
con = New SqlConnection("server=SHREE-PC;database=Hospital;INTEGRATED SECURITY=SSPI;")
con.Open()
‘ cmd = New SqlCommand("select * from Doctor", con)
str = "insert into Doctor values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "' )"
cmd = New SqlCommand(str, con)
count = cmd.ExecuteNonQuery()
MessageBox.Show(count & " Record inserted")
con.close()
End Sub
Imports System.Data.SqlClient
Public Class Form4
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim str As String
Dim count As Integer
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
con = New SqlConnection("server=SHREE-PC;database=Hospital;INTEGRATED SECURITY=SSPI;")
con.Open()
cmd = New SqlCommand("select * from Patient", con)
cmd = New SqlCommand("Delete from Patient where Name ='" & TextBox1.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Address='" & TextBox2.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Dieses='" & TextBox3.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Patient_no=" & TextBox4.Text & "", con)
‘you can take any row in your program
count = cmd.ExecuteNonQuery()
MessageBox.Show("Record Deleted")
End Sub

Visual Basic 2008 New Search Query

I'm trying to do a search through an access database I added to a project but I get this error: An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll"
Additional information: No value given for one or more required parameters.
The idea was to search the database for text entered into a textbox, then display the information on that row within more text boxes.
The code dr = cmd.ExecuteReader is also highlighted as an issue when debugging. I'm using visual basic 2008, and quite new to the whole coding scene so explanations as to why the issue has occurred would be appreciated!
Imports System.Windows.Forms
Imports System.Data.OleDb
Public Class frmSearch
Public con As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Dim dbProvider As String
Dim dbSource As String
Dim BillingSystemFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Private Sub frmSearch_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'BillingdatabaseDataSet.BillingInfo' table. You can move, or remove it, as needed.
Me.BillingInfoTableAdapter.Fill(Me.BillingdatabaseDataSet.BillingInfo)
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
'Setup the provider
TheDatabase = "/billingdatabase.accdb"
BillingSystemFolder = Application.StartupPath
FullDatabasePath = BillingSystemFolder & TheDatabase
'Set the database and the location of it
dbSource = "Data Source = " & FullDatabasePath
'Set the data source
con.ConnectionString = dbProvider & dbSource
'Set the connection string
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
con.Open()
txtJobNum.Clear()
txtName.Clear()
txtSurname.Clear()
Dim str As String
str = "SELECT * FROM BillingInfo WHERE (Code = " & CodeText.Text & ")"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
dr = cmd.ExecuteReader
While dr.Read()
txtSurname.Text = dr("Surname").ToString
txtName.Text = dr("First Name").ToString
txtJobID.Text = dr("Customer ID").ToString
End While
con.Close()
End Sub
End Class
Probably the field Code is a text field. In this case when you want to search using a particular value for that field you should enclose the value between single quotes.
Something like this
str = "SELECT * FROM BillingInfo WHERE (Code = '" & CodeText.Text & "')"
However this is really a bad practice because this allows to create an Sql Injection attack or it will simply fail because your value contains a single quote.
The correct method is using a parameterized query like this
str = "SELECT * FROM BillingInfo WHERE (Code = #p1)"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = CodeText.Text
dr = cmd.ExecuteReader