ms access 2010 and vs2010 how to connect - visual-studio-2010

Program crash in cmd.ExecuteNonQuery() row
Public Class Form1
Dim conn As New OleDb.OleDbConnection
Private Sub RefreshData()
If Not conn.State = ConnectionState.Open Then
'open connection
conn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT Oznaka as [Oznaka], " & _
"ReN as [ReN], RmN " & _
" FROM Tabela ORDER BY Oznaka", conn)
Dim dt As New DataTable
'fill data to datatable
da.Fill(dt)
'offer data in data table into datagridview
Me.DataGridView1.DataSource = dt
'close connection
conn.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As New OleDb.OleDbCommand
If Not conn.State = ConnectionState.Open Then
'open connection if it is not yet open
conn.Open()
End If
cmd.Connection = conn
'check whether add new or update
If Me.txtOznaka.Tag & "" = "" Then
'add new
'add data to table
cmd.CommandText = "INSERT INTO Tabela(Oznaka, ReN, RmN) " & _
" VALUES('" & Me.txtOznaka.Text & "','" & Me.txtReN.Text & "','" & _
Me.txtRmN.Text & "'')"
cmd.ExecuteNonQuery()
Else
'update data in table
cmd.CommandText = "UPDATE Tabela " & _
" SET Oznaka=" & Me.txtOznaka.Text & _
", ReN='" & Me.txtReN.Text & "'" & _
", RmN='" & Me.txtRmN.Text & "'" & _
" WHERE Oznaka=" & Me.txtOznaka.Tag
cmd.ExecuteNonQuery()
End If
'refresh data in list
RefreshData()
'clear form
'Me.btnClear.PerformClick()
'close connection
conn.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
conn = New OleDb.OleDbConnection
conn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\baza.mdb"
'
'get data into list
Me.RefreshData()
End Sub
End Class

Are you running the INSERT or the UPDATE query when it crashes?
If it's the INSERT query, it's probably because the SQL string has one ' too much at the end:
... Me.txtRmN.Text & "'')"
^
here!
If it's the UPDATE query: if Oznaka is a string column, put the value in quotes:
" SET Oznaka='" & Me.txtOznaka.Text & "'" & _
instead of
" SET Oznaka=" & Me.txtOznaka.Text & _
An even better solution for both of these issues would be: use SQL parameters in your queries instead of concatenating strings.
Here are some examples to get started:
INSERT with transaction and parameters?
Pass a NULL in a parameter to a DateTime field in a stored procedure

Related

i got no error, but : "OleDbException was unhandled Syntax error (missing operator) in query expression" how to solve this?

I am new in creating an application using Visual Stuido 2010 C# and Microsft Access 2007. I am planning to create an application where the user can add data to the database(MS-Access). But I got an error stating that "Syntax Error (missing operator) In Query Expression". I really can't find what's the problem with my code. im using panel for page 2 of my form.
i got the problem from Sub Button1 "rd = cmd.ExecuteReader"
This is my code in adding data to the database:
Imports System.Data.OleDb
Public Class Form1
Dim conn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim str As String
Dim cmd As OleDbCommand
Dim rd As OleDbDataReader
Dim tanya As String
Sub koneksi()
str = "provider=microsoft.jet.oledb.4.0;data source=Database1.mdb"
conn = New OleDbConnection(str)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
End Sub
Sub tampilkan()
da = New OleDbDataAdapter("select * from tb_bpl", conn)
ds = New DataSet
da.Fill(ds, "tb_bpl")
DataGridView1.DataSource = ds.Tables("tb_bpl")
DataGridView1.Columns(1).Width = 250
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call koneksi()
Call tampilkan()
End Sub
Private Sub Button4_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Me.Close()
End Sub
Private Sub bersih()
TextBox1.Clear()
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
TextBox9.Text = ""
TextBox10.Text = ""
TextBox11.Text = ""
TextBox12.Text = ""
TextBox13.Text = ""
TextBox14.Text = ""
TextBox15.Text = ""
TextBox16.Text = ""
TextBox17.Text = ""
End Sub
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
cmd = New OleDbCommand("select * tb_bpl where periode='" + TextBox1.Text + "'", conn)
rd = cmd.ExecuteReader
rd.Read()
If Not rd.HasRows Then 'jika data/baris tidak ditemukan
Dim simpan As String = "insert into tb_bpl(periode, reviewer, pemeriksa, paraf1, paraf2, y1, kkp1, ket1, y2, kkp2, ket2, y3, kkp3, ket3, y4, kkp4, ket4) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & "','" & TextBox9.Text & "','" & TextBox10.Text & "','" & TextBox11.Text & "','" & TextBox12.Text & "','" & TextBox13.Text & "','" & TextBox14.Text & "','" & TextBox15.Text & "','" & TextBox16.Text & "','" & TextBox17.Text & "')"
cmd = New OleDbCommand(simpan, conn)
cmd.ExecuteNonQuery()
MsgBox("Data Baru Tersimpan", vbInformation, "Pemberitahuan!!!")
Call bersih()
Else
MsgBox("Data Sudah Ada", vbInformation, "Maaf!!!")
End If
tampilkan()
End Sub
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
cmd = New OleDbCommand("select * from tb_bpl where periode='" & TextBox1.Text & "'", conn)
rd = cmd.ExecuteReader
rd.Read()
If rd.HasRows Then
Dim sqledit As String = "update tb_bpl set reviewer='" & TextBox2.Text & "',pemeriksa='" & TextBox3.Text & "',paraf1='" & TextBox4.Text & "',paraf2='" & TextBox5.Text & "',y1='" & TextBox6.Text & "' ,kkp1='" & TextBox7.Text & "' ,ket1='" & TextBox8.Text & "',y2='" & TextBox9.Text & "',kkp2='" & TextBox10.Text & "',ket2='" & TextBox11.Text & "',y3='" & TextBox12.Text & "',kkp3='" & TextBox13.Text & "',ket3='" & TextBox14.Text & "',y4='" & TextBox15.Text & "',kkp4='" & TextBox16.Text & "',ket4='" & TextBox17.Text & "' where periode='" & TextBox1.Text & "'"
cmd = New OleDbCommand(sqledit, conn)
cmd.ExecuteNonQuery()
End If
MsgBox("Data Terubah", vbOKOnly, "Sukses")
Call bersih()
Call tampilkan()
End Sub
Private Sub Button3_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
cmd = New OleDbCommand("select * from tb_bpl where periode='" & TextBox1.Text & "'", conn)
rd = cmd.ExecuteReader
rd.Read()
If rd.HasRows Then
tanya = MsgBox("Anda Yakin Akan Menghapus Data?", vbYesNo, "Perhatian")
If tanya = vbYes Then
Dim sqlhapus As String = "delete * from tb_bpl where periode='" & TextBox1.Text & "'"
cmd = New OleDbCommand(sqlhapus, conn)
cmd.ExecuteNonQuery()
MsgBox("Data Terhapus", vbOKOnly, "Sukses")
Call bersih()
End If
End If
Call tampilkan()
End Sub
Private Sub TextBox1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs)
cmd = New OleDbCommand("select * from tb_bpl where periode='" & TextBox1.Text & "'", conn)
rd = cmd.ExecuteReader
rd.Read()
If rd.HasRows Then
TextBox2.Text = rd.Item("reviewer")
TextBox3.Text = rd.Item("pemeriksa")
TextBox4.Text = rd.Item("paraf1")
TextBox5.Text = rd.Item("paraf2")
TextBox6.Text = rd.Item("y1")
TextBox7.Text = rd.Item("kkp1")
TextBox8.Text = rd.Item("ket1")
TextBox9.Text = rd.Item("y2")
TextBox10.Text = rd.Item("kkp2")
TextBox11.Text = rd.Item("ket2")
TextBox12.Text = rd.Item("y3")
TextBox13.Text = rd.Item("kkp3")
TextBox14.Text = rd.Item("ket3")
TextBox15.Text = rd.Item("y4")
TextBox16.Text = rd.Item("kkp4")
TextBox17.Text = rd.Item("ket4")
End If
End Sub
End Class

Trouble displaying the content of DataGrid

Hi can i ask someone on how to easily display the content of my database using dataGridView, I already managed to update the inputted datas into the database. can you also give me some tips on my project.
I am using access as My database
Imports System.Data.OleDb
Imports System.Data
Public Class stor
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Validate()
Me.StorBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Database7DataSet)
If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Then
MsgBox("Please Complete all the Information")
Else
Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Gui\Documents\Database7.accdb;")
Dim insert As String = "Insert into stor values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
cmd.ExecuteNonQuery()
MsgBox("create success")
Catch ex As Exception
MsgBox("error")
End Try
End If
End Sub
Private Sub stor_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database7DataSet.stor' table. You can move, or remove it, as needed.
Me.StorTableAdapter.Fill(Me.Database7DataSet.stor)
End Sub
End Class
Click Here to view my project

How to add row value to the combobox

I have a table name 'product', and product_name, category as a fields. I want to add the product_name row value to the combobox where the category value is repeated....
product_name | category
--------------+----------
Ceiling fan | fan
Table fan | fan
Wall fan | fan
I try the following code but without do while statement it gives one value and when i am trying to loop it the machine hangs. Plz help
Option explicit
Private sub cboCategories_Click()
cboProducts.clear
rs.open "select * from product". cn, adOpenDynamic. adLockOptimistic
With rs
.find "category=' " & cbiCategories.Text & " ' "
.moveFirst
With rs(0).value
Do until rs.EOF
cboProducts.AddItem rs(0).Value
rs.MoveNext
Loop
End with
End with
End sub
This is my table at present. I want to get the product_name field value to the combobox where the category name is the same, such as 'fan'
There are several ways to skin such a cat. One is to source your ComboBox data from a disconnected hierarchical Recordset created using the Data Shaping Service.
This example assumes a CSV file with a header row, but the same thing works with a Jet or other database table:
Option Explicit
Private rsShapedProducts As ADODB.Recordset
Private Sub cboCategories_Click()
With cboProducts
.Clear
With rsShapedProducts
.MoveFirst
.Find "[Category]='" & cboCategories.List(cboCategories.ListIndex) & "'"
With ![Products].Value
.MoveFirst
Do Until .EOF
cboProducts.AddItem ![Product].Value
.MoveNext
Loop
End With
End With
.ListIndex = 0
End With
End Sub
Private Sub cboProducts_Click()
lblSelection.Caption = cboCategories.List(cboCategories.ListIndex) _
& " -> " _
& cboProducts.List(cboProducts.ListIndex)
End Sub
Private Sub Form_Load()
Set rsShapedProducts = New ADODB.Recordset
With rsShapedProducts
.CursorLocation = adUseClient
.Open "SHAPE {" _
& "SELECT [Category], [Product] FROM [products.txt] " _
& "ORDER BY [Category], [Product]" _
& "} AS [Products] COMPUTE [Products] BY [Category]", _
"Provider=MSDataShape;Data Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source='" & App.Path & "';Extended Properties='Text;Hdr=Yes'", _
adOpenStatic, _
adLockReadOnly, _
adCmdText
Set .ActiveConnection = Nothing
Do Until .EOF
cboCategories.AddItem ![Category].Value
.MoveNext
Loop
End With
Show
cboCategories.ListIndex = 0
End Sub
Private Sub Form_Unload(Cancel As Integer)
rsShapedProducts.Close
End Sub
Test data I used:
Category,Product
Fan,Ceiling Fan
Fan,Table Fan
Fan,Wall Fan
Lamp,Floor Lamp
Lamp,Table lamp
Lamp,Desk Lamp
Table,Coffee Table
Table,End Table
Table,Kitchen Table
Table,Dining Table
Table,Card Table
Private Function IsInCollection(ByVal Coll As Collection, CollKey As String) As Boolean
On Error GoTo errHandler
Dim b As Variant
b = Coll(CollKey)
IsInCollection = True
errHandler:
Err.Clear
Exit Function
End Function
Public Sub FillCombo()
Dim rs As Adodb.Recordset
Dim Coll As New Collection
Dim strNewValue As String
Set rs = fillMyRs
Do While Not rs.EOF
strNewValue = rs.Fields("category").Value
If IsInCollection(Coll, strNewValue) Then
strNewValue = strNewValue & " - " & rs.Fields("product_name").Value
Else
Coll.Add strNewValue, strNewValue
End If
Combo1.AddItem strNewValue
rs.MoveNext
Loop
End Sub

VB6.0 with DataControl Database Programming

can you help out access the database... I have been reading some tutorials but I don't know where to start doing this one. I used DataControl to access the database. First, the program will prompt for the ID Number and then Search for the further information and display it in texboxes when Search Employee button clicked. I know how to set the properties of textboxes in order to appear the value of my database to my output without clicking the Search Employee button but I want to click first the button Search Employee. I'm a beginner in VB6. Please help me out! I need this project now.
Ok, I had some time to spare, here you go, first add a reference to Microsoft ActiveX Data Objects 2.X Library:
Form1 Code:
Option Explicit
''Add the following items to your form and name them as indicated:
''Four(4) text boxes - Named: tbIDNumber, tbName, tbAddress, and tbContactName.
''One(1) Command button - Named Command1
Private Sub Command1_Click()
Dim rs As ADODB.Recordset
Dim DB As cDatabase
Dim l As Long
Set rs = New ADODB.Recordset
Set DB = New cDatabase
With DB
.DBCursorType = adOpenForwardOnly
.DBLockType = adLockReadOnly
.DBOptions = adCmdText
.DSNName = "Your_DSN_Name"
.SQLUserID = "Your_SQL_Login_Name"
.SQLPassword = "Your_SQL_Login_Password"
Set rs = .GetRS("Select Name, Address, ContactNumber FROM YourTableName WHERE IDNumber = '" & tbIDNumber.Text & "'")
End With
If rs.RecordCount > 0 Then
tbName.Text = rs(0).Value & ""
tbAddress.Text = rs(1).Value & ""
tbContactName.Text = rs(2).Value & ""
End If
Exit_Sub:
rs.Close
Set rs = Nothing
Set DB = Nothing
End Sub
Add a Class Module Object to your project and name it cDatabase. Then copy the following Code into it:
Option Explicit
Private m_eDBCursorType As ADODB.CursorTypeEnum 'Cursor (Dynamic, Forward Only, Keyset, Static)
Private m_eDBLockType As ADODB.LockTypeEnum 'Locks (BatchOptimistic,Optimistic,Pessimistic, Read Only)
Private m_eDBOptions As ADODB.CommandTypeEnum 'DB Options
Private m_sDSNName As String
Private m_sSQLUserID As String
Private m_sSQLPassword As String
Private cn As ADODB.Connection
Private Sub Class_Initialize()
m_eDBCursorType = adOpenForwardOnly
m_eDBLockType = adLockReadOnly
m_eDBOptions = adCmdText
End Sub
Private Function ConnectionString() As String
ConnectionString = "DSN=" & m_sDSNName & "" & _
";UID=" & m_sSQLUserID & _
";PWD=" & m_sSQLPassword & ";"
''If you are using MS Access as your back end you will need to change the connection string to the following:
''ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
''If you are using a DNS-Less connection to SQL Server, then you will need to change the connection string to the following:
''ConnectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=" & m_sSQLUserID & ";Password=" & m_sSQLPassword & ";"
''You can find more Connection Strings at http://connectionstrings.com/
End Function
Private Sub GetCN()
On Error GoTo GetCN_Error
If cn.State = 0 Then
StartCN:
Set cn = New ADODB.Connection
cn.Open ConnectionString
With cn
.CommandTimeout = 0
.CursorLocation = adUseClient
End With
End If
On Error GoTo 0
Exit Sub
GetCN_Error:
If Err.Number = 91 Then
Resume StartCN
Else
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure GetCN of Module modDatabaseConnections"
End If
End Sub
Public Function GetRS(sSQL As String) As ADODB.Recordset
Dim eRS As ADODB.Recordset
On Error GoTo GetRS_Error
TryAgain:
If Len(Trim(sSQL)) > 0 Then
Call GetCN
Set eRS = New ADODB.Recordset 'Creates record set
eRS.Open sSQL, cn, m_eDBCursorType, m_eDBLockType, m_eDBOptions
Set GetRS = eRS
Else
MsgBox "You have to submit a SQL String"
End If
On Error GoTo 0
Exit Function
GetRS_Error:
If Err.Number = 91 Then
Call GetCN
GoTo TryAgain
ElseIf Err.Number = -2147217900 Then
Exit Function
Else
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure GetRS of Module" & vbCrLf & vbCrLf & "SQL - " & sSQL
End If
End Function
Public Property Get DBOptions() As ADODB.CommandTypeEnum
DBOptions = m_eDBOptions
End Property
Public Property Let DBOptions(ByVal eDBOptions As ADODB.CommandTypeEnum)
m_eDBOptions = eDBOptions
End Property
Public Property Get DBCursorType() As ADODB.CursorTypeEnum
DBCursorType = m_eDBCursorType
End Property
Public Property Let DBCursorType(ByVal eDBCursorType As ADODB.CursorTypeEnum)
m_eDBCursorType = eDBCursorType
End Property
Public Property Get DBLockType() As ADODB.LockTypeEnum
DBLockType = m_eDBLockType
End Property
Public Property Let DBLockType(ByVal eDBLockType As ADODB.LockTypeEnum)
m_eDBLockType = eDBLockType
End Property
Public Property Get DSNName() As String
DSNName = m_sDSNName
End Property
Public Property Let DSNName(ByVal sDSNName As String)
m_sDSNName = sDSNName
End Property
Public Property Get SQLUserID() As String
SQLUserID = m_sSQLUserID
End Property
Public Property Let SQLUserID(ByVal sSQLUserID As String)
m_sSQLUserID = sSQLUserID
End Property
Public Property Get SQLPassword() As String
SQLPassword = m_sSQLPassword
End Property
Public Property Let SQLPassword(ByVal sSQLPassword As String)
m_sSQLPassword = sSQLPassword
End Property
This should do the trick.

How can I upload a file to an Oracle BLOB field using VB6?

I want to take a file from disk and upload it into an Oracle BLOB field, using VB6. How can I do that?
Answering my own question, for reference:
Public Function SaveFileAsBlob(fullFileName As String, documentDescription As String) As Boolean
'Upload a binary file into the database as a BLOB
'Based on this example: http://www.codeguru.com/forum/printthread.php?t=337027
Dim rstUpload As ADODB.Recordset
Dim pkValue AS Long
On Error GoTo ErrorHandler
Screen.MousePointer = vbHourglass
'Create a new record (but leave document blank- we will update the doc in a moment)
'the where clause ensures *no* result set; we only want the structure
strSQL = "SELECT DOC_NUMBER, DOC_DESC, BLOB_FIELD " & _
" FROM MY_TABLE " & _
" WHERE PRIMARY_KEY = 0"
pkValue = GetNextPKValue
Set rstUpload = New ADODB.Recordset
With rstUpload
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open strSQL, myConn
.AddNew Array("DOC_NUMBER", "DOC_DESC"), _
Array(pkValue, documentDescription)
.Close
End With
'They may have the document open in an external application. Create a copy and work with that copy
Dim tmpFileName As String
tmpFileName = GetTempPath & ExtractFileName(fullFileName)
'if the tmp file exists, delete it
If Len(Dir(tmpFileName)) > 0 Then
Kill tmpFileName
End If
'see this URL for info about this subroutine:
'http://stackoverflow.com/questions/848087/how-can-i-copy-an-open-file-using-vb6
CopyFileEvenIfOpen fullFileName, tmpFileName
'Now that our record is inserted, update it with the file from disk
Set rstUpload = Nothing
Set rstUpload = New ADODB.Recordset
Dim st As ADODB.Stream
rstUpload.Open "SELECT BLOB_FIELD FROM MY_TABLE WHERE PRIMARY_KEY = " & pkValue
, myConn, adOpenDynamic, adLockOptimistic
Set st = New ADODB.Stream
st.Type = adTypeBinary
st.Open
st.LoadFromFile (tmpFileName)
rstUpload.Fields("BLOB_FIELD").Value = st.Read
rstUpload.Update
'Now delete the temp file we created
Kill (tmpFileName)
DocAdd = True
ExitPoint:
On Error Resume Next
rstUpload.Close
st.Close
Set rstUpload = Nothing
Set st = Nothing
Screen.MousePointer = vbDefault
Exit Function
ErrorHandler:
DocAdd = False
Screen.MousePointer = vbDefault
MsgBox "Source: " & Err.Source & vbCrLf & "Number: " & Err.Number & vbCrLf & Err.Description, vbCritical, _
"DocAdd Error"
Resume ExitPoint
End Function

Resources