Optional Parameters

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
21,886
Say or example I wanted to do this without parameters.

Code:
Sql = "Select firstName, Lastname, iDNumber from tblCustomers"

Code:
/// <method>
/// Select Query
/// </method>
public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter)
{
	SqlCommand myCommand = new SqlCommand();
	DataTable dataTable = new DataTable();
	dataTable = null;
	DataSet ds = new DataSet();
	try {
		myCommand.Connection = openConnection();
		myCommand.CommandText = _query;
		myCommand.Parameters.AddRange(sqlParameter);
		myCommand.ExecuteNonQuery();
		myAdapter.SelectCommand = myCommand;
		myAdapter.Fill(ds);
		dataTable = ds.Tables(0);
	} catch (SqlException e) {
		Console.Write("Error - Connection.executeSelectQuery - Query: " + _query + " " + Constants.vbLf + "Exception: " + e.StackTrace.ToString());
		return null;

	} finally {
	}
	return dataTable;
}

How would I pass in a blank parameter? Do I need to overload the function instead, without the params?
 
Last edited:

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
21,886
Nevermind, think I solved it.

Code:
   Public Function GetData(ByVal sqlScript As [String], Optional ByVal sqlParameter As SqlParameter() = Nothing) As DataTable

        Dim dataTable As New DataTable
        Try
            Using sqlDataAdapter As New SqlDataAdapter

                sqlDataAdapter.SelectCommand = New SqlCommand()
                sqlDataAdapter.SelectCommand.Connection = openConnection()
                sqlDataAdapter.SelectCommand.CommandType = CommandType.Text
                sqlDataAdapter.SelectCommand.CommandText = sqlScript
                If sqlParameter IsNot Nothing Then
                    sqlDataAdapter.SelectCommand.Parameters.AddRange(sqlParameter)
                End If

                sqlDataAdapter.Fill(dataTable)

            End Using

        Catch e As SqlException
            Console.Write("Error - Query: " + sqlScript + " " & vbLf & "Exception: " + e.StackTrace.ToString())
            Return Nothing

        Finally

        End Try
        Return dataTable

    End Function
 

Webnoob

Member
Joined
Jul 6, 2016
Messages
16
Jesus Christ when will ppl move away from DataTable/DataSet etc? It's horrific to use...
 
Top