PDA

View Full Version : Inserting an aprostrophe into an Ms access database


Mistery1
Apr 29, 2009, 03:27 AM
Hi there,

I have the ffg code so far, which inserts info into the database. But how do I go about inserting/ writing code to insert a surname like O'Reily (take not of the aprostrophe) into the database.

Imports System.Data.OleDb
Public Class Form1

Public cn As OleDbConnection
'Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim icount As Integer
Dim str As String


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Mogie\Desktop\Emp.mdb;")
cn.Open()
str = "insert into table1 values(" & CInt(EmpNo.Text) & ",'" & Ename.Text & "','" & Department.Text & "')"
'string stores the command and CInt is used to convert number to string
cmd = New OleDbCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
'displays number of records inserted


cn.Close()
End Sub


End Class

Perito
Apr 29, 2009, 07:17 AM
Your problem occurs in this line,

cmd = New OldDbCommand(str, cn)

where the apostrophe is interpreted as terminating the string since the apostrophe is a terminator in MS Access. When you have a name with an apostrophe in it, modify the name string to have two apostrophes in it:

"O'Reilly" becomes "O''Reilly" (that's two apostrophes between the "O" and "R", not a quotation mark).

Mistery1
May 15, 2009, 07:19 AM
Hi There,

Thanks for this, it really helps.