Results 1 to 12 of 12

Thread: How to shift from straight query to parametrized one at module level

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2010
    Posts
    965

    How to shift from straight query to parametrized one at module level

    Hi. I've been using straight query, which had sql injection problem, so i shift over to parametrized one, which i learn in the same forum here.

    Now i want to use the queries at module level, but i'm totally unfamiliar for this that how to use Parametrized queries at module level. I'm using the following code.

    This is my module code, for insert query:
    Code:
    #Region "Insertion"
    
        Public Sub Insertion(ByVal tblName As String, ByVal columns As String, ByVal Parameters As String)
            Try
                cmdsql1.CommandText = "insert into " & tblName & " ( " & columns & ")  values  ( " & Parameters & ")"
                cmdsql1.Connection = Conn()
                cmdsql1.ExecuteNonQuery()
    
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End Sub
    #End Region
    and this is my form button code:
    Code:
    Try
                Insertion("ProductBasicInfo", "ProdId, ProdName, Description, Manufacturer", " " & txtProdID.Text.Trim & ", '" & txtProdName.Text.Trim & "', '" & txtProdDesc.Text.Trim & "', '" & txtProdManuf.Text.Trim & "'")
                MessageBox.Show("Record Inserted Successfully")
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
    My question is that how do i shift again from this query to parametrized once. Normally I'm doing all my work so far with parametrized queries. But this is my first attempt to working at module level, so i don't know that how to apply parametrized at module level. Please guide me.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: How to shift from straight query to parametrized one at module level

    I think that that's a rather dodgy way to implement a DAL but, if that's the way you want to go, I'd do it something like this:
    vb.net Code:
    1. Public Sub Insert(tableName As String, valuesByColumn As IDictionary(Of String, Object))
    2.     Dim escapeChars = {"[", "]"}
    3.  
    4.     'Ensure that the table name contains no escape characters to guard against SQL injection.
    5.     If escapeChars.Any(Function(escapeChar) tableName.Contains(escapeChar)) Then
    6.         Throw New InvalidOperationException("Table name contains invalid characters that suggest possible SQL injection attack.")
    7.     End If
    8.  
    9.     'Ensure that the column names contain no escape characters to guard against SQL injection.
    10.     If valuesByColumn.Keys.Any(Function(columnName) escapeChars.Any(Function(s) columnName.Contains(s))) Then
    11.         Throw New InvalidOperationException("Column name contains invalid characters that suggest possible SQL injection attack.")
    12.     End If
    13.  
    14.     Dim sqlTemplate = "INSERT INTO [{0}] ([{1}]) VALUES ({2})"
    15.     Dim columnList = String.Join("], [", valuesByColumn.Keys)
    16.     Dim parameterList = String.Join(", ", valuesByColumn.Keys.Select(Function(columnName) "@" & columnName))
    17.     Dim command = New SqlCommand(String.Format(sqlTemplate, tableName, columnList, parameterList))
    18.  
    19.     For Each columnName In valuesByColumn.Keys
    20.         'Use DBNull.Value if the parameter value is Nothing.
    21.         command.Parameters.AddWithValue("@" & columnName,
    22.                                         If(valuesByColumn(columnName),
    23.                                            DBNull.Value))
    24.     Next
    25.  
    26.     '...
    27. End Sub
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2010
    Posts
    965

    Re: How to shift from straight query to parametrized one at module level

    Hooo. This is far complex. Its all gone over my head.

    that's a rather dodgy way to implement a DAL
    Would you please guide me that what is better alternative way, and what is DAL?

  4. #4
    Still learning kebo's Avatar
    Join Date
    Apr 2004
    Location
    Gardnerville,nv
    Posts
    3,762

    Re: How to shift from straight query to parametrized one at module level

    jm's code is a bit complicated especially for those trying to learn...
    db command parameters work something like this...

    Code:
    cmd.CommandText = "SELECT * FROM <tableName> WHERE Name=@name and City=@city"
    md.Parameters.Add("@name", OleDbType.VarChar).value = myCity
    cmd.Parameters.Add("@city", OleDbType.VarChar).value =  myState
    you will of course have to adapt it to your code.
    hope this helps. Database programming is not my strong suit.
    Process control doesn't give you good quality, it gives you consistent quality.
    Good quality comes from consistently doing the right things.

    Vague general questions have vague general answers.
    A $100 donation is required for me to help you if you PM me asking for help. Instructions for donating to one of our local charities will be provided.

    ______________________________
    Last edited by kebo : Now. Reason: superfluous typo's

  5. #5

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2010
    Posts
    965

    Re: How to shift from straight query to parametrized one at module level

    Hi Kebo.

    Code:
    cmd.CommandText = "SELECT * FROM <tableName> WHERE Name=@name and City=@city"
    In this line of code, you have particularized 2 fields, received to the function. But in my case, everytime the function receives random number of fields, so how to cope with this?

  6. #6
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,415

    Re: How to shift from straight query to parametrized one at module level

    Quote Originally Posted by ADQUSIT View Post
    Hi Kebo.

    Code:
    cmd.CommandText = "SELECT * FROM <tableName> WHERE Name=@name and City=@city"
    In this line of code, you have particularized 2 fields, received to the function. But in my case, everytime the function receives random number of fields, so how to cope with this?
    the database has a fixed number of fields. you could try something like this:

    Code:
    Imports System.Data.OleDb
    
    Public Class Form1
    
        Dim conn As OleDbConnection
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            conn = New OleDbConnection("connection string")
        End Sub
    
        Private Function getRecords(ByVal tableName As String, ByVal field1 As String, ByVal field2 As String, ByVal field3 As String) As DataTable
            Dim cmd As New OleDbCommand(String.Format("SELECT * FROM {0} WHERE Field1 LIKE @field1 AND Field2  LIKE @field2 AND Field3  LIKE @field3", tableName), conn)
            cmd.Parameters.Add("@field1", OleDbType.VarChar).Value = If(field1 <> "", field1, "*")
            cmd.Parameters.Add("@field2", OleDbType.VarChar).Value = If(field2 <> "", field2, "*")
            cmd.Parameters.Add("@field3", OleDbType.VarChar).Value = If(field3 <> "", field3, "*")
    
            Dim da As New OleDbDataAdapter(cmd)
            Dim dt As New DataTable
            da.Fill(dt)
    
            Return dt
        End Function
    
    End Class

  7. #7

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2010
    Posts
    965

    Re: How to shift from straight query to parametrized one at module level

    @.PAUL

    I"m little confuse here:
    Code:
    Private Function getRecords(ByVal tableName As String, ByVal field1 As String, ByVal field2 As String, ByVal field3 As String) As DataTable
            Dim cmd As New OleDbCommand(String.Format("SELECT * FROM {0} WHERE Field1 LIKE @field1 AND Field2  LIKE @field2 AND Field3  LIKE @field3", tableName), conn)
    Please guide me for this.

    Secondly, how many field parameters i can pass to this function?

  8. #8
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,415

    Re: How to shift from straight query to parametrized one at module level

    what is your tablename + all of your field names + datatypes in that table?
    i'll show you how you can query that table by any combination of fields...

  9. #9

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2010
    Posts
    965

    Re: How to shift from straight query to parametrized one at module level

    Table name = ProductBasicInfo

    ProdId = int, ProdName = varchar, Description = varchar, Manufacturer = varchar

  10. #10
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,415

    Re: How to shift from straight query to parametrized one at module level

    Code:
    Imports System.Data.OleDb
    
    Public Class Form1
    
        Dim conn As OleDbConnection
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            conn = New OleDbConnection("connection string")
        End Sub
    
        Private Function getRecords(ByVal ProdId As Integer, ByVal ProdName As String, ByVal Description As String, ByVal Manufacturer As String) As DataTable
            Dim cmd As New OleDbCommand(String.Format("SELECT * FROM ProductBasicInfo WHERE {0} ProdName LIKE @ProdName AND Description  LIKE @Description AND Manufacturer  LIKE @Manufacturer", If(ProdId <> -1, "ProdId = @ProdId AND ", "")), conn)
            If ProdId <> -1 Then
                cmd.Parameters.Add("@ProdId", OleDbType.Integer).Value = ProdId
            End If
            cmd.Parameters.Add("@ProdName", OleDbType.VarChar).Value = If(ProdName <> "", ProdName, "*")
            cmd.Parameters.Add("@Description", OleDbType.VarChar).Value = If(Description <> "", Description, "*")
            cmd.Parameters.Add("@Manufacturer", OleDbType.VarChar).Value = If(Manufacturer <> "", Manufacturer, "*")
    
            Dim da As New OleDbDataAdapter(cmd)
            Dim dt As New DataTable
            da.Fill(dt)
    
            Return dt
        End Function
    
        'you can use any combination of these (-1 specifies no ProdId, "" specifies ANY in the other fields):
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            'get records by ProdId
            Dim dt As DataTable = getRecords(1, "", "", "")
        End Sub
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            'get records by ProdName
            Dim dt As DataTable = getRecords(-1, "a name", "", "")
        End Sub
    
        Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
            'get records by Description
            Dim dt As DataTable = getRecords(-1, "", "a description", "")
        End Sub
    
        Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
            'get records by Manufacturer
            Dim dt As DataTable = getRecords(-1, "", "", "a manufacturer")
        End Sub
    
    End Class

  11. #11

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2010
    Posts
    965

    Re: How to shift from straight query to parametrized one at module level

    I will try it and will feed back. Thank you sir.

  12. #12

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2010
    Posts
    965

    Re: How to shift from straight query to parametrized one at module level

    Hello Paul.

    You have define the fields of single table in this particular function. But lets say if i have several tables, so how this single function will fulfill my need. Even if i make the same function with different set of parameters (function overloading), how i will separately define the fields in function for n number of tables? Won't this be a cumbersome task to do?

    Isn't there any way, by which I don't need to define the fields for each table (like I'm doing in this way), like i do in straight query method?

    Please guide me if I'm wrong?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width