Sunday, December 13, 2009

Writing SQL Queries from Visual Basic 6

Consider the Oracle relation

customer(cid number(5),first_name varchar2(10),last_name varchar2(10),
ph_no number(10) , address varchar2(25))

Inserting into customer relation from vb6 form:

Assume we enter the following fields in the following controls in the vb form

cid - text1
first_name - text2
last_name - text3
ph_no - text4
address - text5

The following code inserts a new record into the customer table.

Dim oconn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strSQL As String
Dim str As String
Set oconn = New ADODB.Connection
oconn.Open "Provider=msdaora;Data Source=localhost;User Id=paul;Password=oracle;"
oconn.CursorLocation = adUseClient

strSQL = "insert into customer(cid,first_name,last_name,ph_no,address) values(" + Text1.Text + ",' " + Text2.Text + " ',' " + Text3.Text + " '," + Text4.Text + ",' " + Text5.Text + " ') "

oconn.Execute strSQL

The statement,

strSQL = "insert into customer(cid,first_name,last_name,ph_no,address) values(" + Text1.Text + ",' " + Text2.Text + " ',' " + Text3.Text + " '," + Text4.Text + ",' " + Text5.Text + " ') "

inserts a new record.We use the + symbol to concatenate the input data to be inserted into the oracle table.When we want to insert a numeric field we just enclose it with double quotes.This is a part of vb syntax.When we want to insert character or string field ,we first enclose it with
double quotes as a part of vb syntax,then we have to enclose it with single quotes as a part of oracle syntax(oracle requires character or string fields to be entered in single qoutes).

Deleting from customer realtion :

Consider we delete a record based on the entered customer id(cid) value.Let the cid value be entered in textbox1 in the form.The following code deletes a record from the table.

Dim oconn As New ADODB.Connection
Dim f As String
Dim rs As New ADODB.Recordset
Dim strSQL As String
Set oconn = New ADODB.Connection
oconn.Open "Provider=msdaora;Data Source=localhost;User Id=paul;Password=oracle;"
strSQL = "delete from customer where cid=" + Text1.Text + " "
oconn.Execute strSQL

No comments:

Post a Comment