Thread: SQL Tutorial
View Single Post
  #10 (permalink)  
Old 11-08-2009, 02:23 PM
Caravelle Caravelle is offline
Senior Member
 
Join Date: Sep 2009
Location: Surrey, UK
Posts: 111
Default

As I tend to think while I type, I know I can become confused (and confusing) sometimes. Maybe this code will explain what I've now done better than I can

Code:
Sub addRecord
  
' row is a global array containing the row data from the editing screen
  ' col is a global array containing the column names
  ' p1, p2 etc are the command parameters, the number part matching the index of the relevant column in row()
  ' tableName is a global variable
  Connection.BeginTransaction 
    
For i = 1 To ArrayLen(row()) - 1
      Command.AddParameter(
"p" & i)
      Command.SetParameter(
"p" & i, row(i))
    
Next    
    Command.CommandText = 
"INSERT INTO " & tableName & " VALUES (null, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8)"
    
' nb although a null is seemingly put in the ID column a unique value will be supplied by sqlite
    Command.ExecuteNonQuery        
  Connection.EndTransaction
End Sub

Sub updateRecord
  
' row is a global array containing the row data from the editing screen
  ' col is a global array containing the column names
  ' tableName is a global variable
  Connection.BeginTransaction
    
For i = 0 To ArrayLen(row()) - 1
      Command.AddParameter(
"p" & i)
      Command.SetParameter(
"p" & i, row(i))
    
Next
    
' p is shorthand for string "=@p" - saves confusion about quote marks
    p = "=@p"
    
' q is a temporary holder for Command.CommandText - (q for query string)
    q = "UPDATE " & tableName & " SET "
    
For i = 1 To ArrayLen(row()) - 2
      q = q & col(i) & p & i & 
""
    
Next
    q = q & col(i) & p & i & 
" WHERE " & col(0) & "=@p0"    
    Command.CommandText = q
    Command.ExecuteNonQuery    
    Connection.EndTransaction
End Sub

Sub deleteRecord    
  Connection.BeginTransaction
    
' assumes the ID will always be the first column - name stored in col(0), value in row(0)
    ' row is a global array containing the row data from the editing screen
    ' col is a global array containing the column names
    ' tableName is a global variable
    Command.AddParameter("p0")    
    Command.SetParameter(
"p0" , row(0))
    Command.CommandText = 
"DELETE FROM " & tableName & " WHERE " & col(0) & "=@p0"
    Command.ExecuteNonQuery        
  Connection.EndTransaction
End Sub
So long as you set up your arrays at the start of your progam, these subs should work for any single table. The arrays could even be filled from an .ini file, which could also set table column widths.

I hope that helps.

Caravelle
__________________
Caravelle
I learn by my mistakes - so I learn a lot in a short time.
Reply With Quote