Please see below code (issue with handling null values)
Dts.Variables("File_Name").Value = Framework.GetValue("FileName")
Dts.Variables("File_Id").Value = Framework.GetValue("FileName")
Dts.Variables("File_Name").Value - Data type defined in STRING
Dts.Variables("File_Id").Value - Data type defined in INTEGER
Framework.GetValue - Returns STRING (fetches value stored in database)
Problem - when Framework.GetValue returns nothing because value doesn't exist in database, it throws error in SSIS Script component. How to capture NULL is the problem we are facing
Public Function GetValue(ByVal FetchParameter As String) As String
Dim lGetValue As String = String.Empty
Using Conn New SqlConnection(ConnString)
SQLCommand = New SqlCommand("ParameterValues", _ETLFrameworkConn)
SQLCommand.CommandText = "Select ParamValue from ParameterValues where Parameter_Name=#ParameterField"
SQLCommand.Parameters.Add(New SqlParameter("#ParameterField").Value SqlDbType.NVarChar))
SQLCommand.Parameters("#ParameterField").Value = FetchParameter
Try
Conn.Open()
lGetValue = SQLCommand.ExecuteScalar()
Catch ex As Exception
End Try
End Using
Return lGetValue
End Function
Regards
Try the following code snippet in you GetValue() function. Added the DBNULL handling into the code. If there is no value String.Empty will be written.
Dim lGetValue As String = String.Empty
Using Conn New SqlConnection(ConnString)
SQLCommand = New SqlCommand("ParameterValues", _ETLFrameworkConn)
SQLCommand.CommandText = "Select ParamValue from ParameterValues where Parameter_Name=#ParameterField"
SQLCommand.Parameters.Add(New SqlParameter("#ParameterField").Value SqlDbType.NVarChar))
SQLCommand.Parameters("#ParameterField").Value = FetchParameter
Try
Conn.Open()
var retrunVal = (string)SQLCommand.ExecuteScalar()
IF returnVal = DBNULL.Value Then
lGetValue = returnVal
End
Catch ex As Exception
End Try
End Using
Return lGetValue
Hope this helps!
Related
Public Function Does_User_Exist(ByVal strEmpId As String) As Boolean
Try
Dim strSQL As String = "DATA.DOES_USER_EXIST"
Dim cmd As OracleCommand = dba.CreateStoredProcCommand(strSQL)
cmd.Connection.Open()
If cmd.Connection.State = ConnectionState.Open Then
With cmd
' CRASHING ON NEXT LINE. I CHANGED THE ORDER AND MADE IT ALL CAPS.
.Parameters.Add(name:="EMPLOYEE", dbType:=OracleClient.OracleType.VarChar, size:=8).Value = strEmpId
.Parameters.Add(name:="ROWCOUNT", dbType:=OracleClient.OracleType.Number).Direction = ParameterDirection.Output
End With
dba.ExecuteScaler(cmd)
If cmd.Parameters("RowCount").Value.ToString = 1 Then
Return True
Else
Return False
End If
End If
Catch ex As Exception
Dim DATAErr As New DATA_Errors("DATA_Users", "Does_User_Exist", ex)
Return False
Finally
End Try
End Function
I checked the connection state and it's Open
Message = "Object reference not set to an instance of an object."
"Oracle.DataAccess"
I am not sure what else to do. I am migrating to ODP.NET from the deprecated Microsoft/Oracle class.
I think the issue is coming from the Parameters. Not sure how to solve it
Public Function CreateStoredProcCommand(ByVal cmdtext As String) As OracleCommand
Dim Cmd As New OracleCommand ' command object ...
' create command ...
With Cmd
.Connection = Conn
.CommandText = cmdtext
.CommandType = CommandType.StoredProcedure
End With
Return Cmd
End Function
I updated the code above to look like this
With cmd
.Parameters.Add(New OracleParameter(parameterName:="EMPLOYEE", type:=OracleClient.OracleType.VarChar, size:=8)).Value = strEmpId
.Parameters.Add(New OracleParameter(parameterName:="ROWCOUNT", oraType:=OracleClient.OracleType.Number)).Direction = ParameterDirection.Output
End With
new Error message at runtime is
{"Specified argument was out of the range of valid values."}
What is out of range? How do I check the value?
Old Code
With cmd
' CRASHING ON NEXT LINE. I CHANGED THE ORDER AND MADE IT ALL CAPS.
.Parameters.Add(name:="EMPLOYEE", dbType:=OracleClient.OracleType.VarChar, size:=8).Value = strEmpId
.Parameters.Add(name:="ROWCOUNT", dbType:=OracleClient.OracleType.Number).Direction = ParameterDirection.Output
End With
New Code
Dim oracleParameter(1) As OracleParameter
oracleParameter(0) = New OracleParameter()
oracleParameter(1) = New OracleParameter()
oracleParameter(0) = cmd.Parameters.Add("EMPLOYEE", dbType:=Oracle.DataAccess.Client.OracleDbType.Varchar2, size:=8, val:=strEmpId, ParameterDirection.Input)
oracleParameter(1) = cmd.Parameters.Add("ROWCOUNT", dbType:=Oracle.DataAccess.Client.OracleDbType.Int16, val:=strEmpId, ParameterDirection.Output)
The actual cause was using the Microsoft Implementation of Oracle Type vs Oracle Type
Let me say that i want to return some array by using this method
Function getKategori() As String()
Dim a As String() = {}
Try
connection.Open()
Dim myCommand As New MySqlCommand
myCommand.Connection = connection
myCommand.CommandText = "SELECT * FROM kategori"
myAdapter.SelectCommand = myCommand
reader = myCommand.ExecuteReader
While reader.Read()
a = {reader(0).ToString, reader(1).ToString}
End While
Catch ex As Exception
End Try
Return a
End Function
it should be return as like
{{a,b},{a,b}} etc, and i want to use that result into combo box by using foreach method
For Each k In x.getKategori()
'?some function to add these items into combobox?
Next
How should i do for it?
Can't get my query to work. I want to pass either integer value or dbnull to my query but in that form is not working. Below my code.
Query:
Using cmd As New SqlCommand("SELECT COUNT(*) FROM tbSuSubSections_Sentences WHERE FK_Sentence_Id = #FK_Sentence_Id And FK_SubSection_Id = #FK_SubSection_Id And FK_SubSubKategorie_Id=#FK_SubSubKategorie_Id", con)
Parameter set up based on which one i need:
If _FK_SubSubKategorie_Id = 0 Then
cmd.Parameters.AddWithValue("#FK_SubSubKategorie_Id", DBNull.Value)
Else
cmd.Parameters.AddWithValue("#FK_SubSubKategorie_Id", _FK_SubSubKategorie_Id)
End If
if _FK_SubSubKategorie_Id is set to DBNull as shown my query should change a bit instead this part:
And FK_SubSubKategorie_Id=#FK_SubSubKategorie_Id", con)
to
And FK_SubSubKategorie_Id IS NULL", con)
What is the right way to do?
that's entire SQL function:
#Region "Check if connection already exist"
Public Function CheckIfConnectionAlreadyExist(_FK_Sentence_Id As Integer, _FK_SubSection_Id As Integer, _FK_SubSubKategorie_Id As Integer) As Boolean
Dim result As Boolean
Dim strcon = New AppSettingsReader().GetValue("ConnectionString", GetType(String)).ToString()
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand("SELECT COUNT(*) FROM tbSuSubSections_Sentences WHERE FK_Sentence_Id = #FK_Sentence_Id And FK_SubSection_Id = #FK_SubSection_Id And FK_SubSubKategorie_Id=#FK_SubSubKategorie_Id", con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#FK_Sentence_Id", _FK_Sentence_Id)
cmd.Parameters.AddWithValue("#FK_SubSection_Id", _FK_SubSection_Id)
If _FK_SubSubKategorie_Id = 0 Then
cmd.Parameters.AddWithValue("#FK_SubSubKategorie_Id", DBNull.Value)
Else
cmd.Parameters.AddWithValue("#FK_SubSubKategorie_Id", _FK_SubSubKategorie_Id)
End If
con.Open()
Dim o As Integer = cmd.ExecuteScalar()
If o > 0 Then
result = True
Else
result = False
End If
con.Close()
End Using
End Using
Return result
End Function
#End Region
Just create one query string which both conditions have in common and change it regarding _FK_SubSubKategorie_Id afterwards. Then create the command:
Dim qry as String = "SELECT COUNT(*) FROM tbSuSubSections_Sentences WHERE FK_Sentence_Id = #FK_Sentence_Id And FK_SubSection_Id = #FK_SubSection_Id And FK_SubSubKategorie_Id {0}"
If _FK_SubSubKategorie_Id = 0 Then
qry = string.Format(qry," IS NULL")
Else
qry = string.Format(qry, "=#FK_SubSubKategorie_Id"
End if
Using cmd As New SqlCommand(qry, con)
...
Help, I am using SQL Server as my database, and my back-end is VB.NET.
I want to assign the value of this query:
SELECT sum(productPrice) from cartTbl
to a variable, and then give the value to a textbox called totalPrice.
How do I perform this? Thank you in advance!
you can use
SELECT #var1=sum(productPrice) from cartTbl
Use an alias for your calculated column
SELECT sum(productPrice) as prod_sum
from cartTbl
Then you can read it like this
While dr.Read()
totalPrice.Text = dr("prod_sum")
End While
It is as simple as this, but please read some basic info on ADO.NET
Using con = new SqlConnection(.....constring here ....)
Using cmd = new SqlCommand("SELECT sum(productPrice) from cartTbl", con)
con.Open()
Dim result = cmd.ExecuteScalar()
Console.WriteLine(result)
End Using
End Using
You should use ExecuteScalar() if using ADO.NET
Public Function GetProductPrice() As Integer
Dim ProdPrice As Int32 = 0
Dim sql As String = "SELECT sum(productPrice) from cartTbl"
Using conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(sql, conn)
Try
conn.Open()
ProdPrice = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
Return ProdPrice
End Function
You can then call this method to get the Price.
Dim prodPrice = GetProductPrice()
To expand on what has already been said, you could use the following to make it a little more flexable:
Private Sub Test()
'Get/set connection string
Me.TextBox1.Text = Me.SQLExecuteScalar(ConnectionString, "SELECT sum(productPrice) FROM cartTbl")
End Sub
Public Shared Function SQLExecuteScalar(ByVal ConnectionString As String, ByVal Query As String) As String
Dim Result As String = Nothing
Dim Exc As Exception = Nothing
Using Conn As New SqlClient.SqlConnection(ConnectionString)
Try
'Open the connection
Conn.Open()
'Create the SQLCommand
Using Cmd As New SqlClient.SqlCommand(Query, Conn)
'Create an Object to receive the result
Dim Obj As Object = Cmd.ExecuteScalar
If (Obj IsNot Nothing) AndAlso (Obj IsNot DBNull.Value) Then
'If Obj is not NULL
Result = Obj.ToString
End If
End Using
Catch ex As Exception
'Save error so we can (if needed) close the connection
Exc = ex
Finally
'Check if connection is closed
If Not Conn.State = ConnectionState.Closed Then
Conn.Close()
End If
End Try
End Using
'Check if any errors where found
If Exc IsNot Nothing Then
Throw Exc
End If
Return Result
End Function
I am trying to pass gridview data into database. The problem I am having is that not all data in my gridview is entering the database. Doing a messagebox shows only name column is going in. Here is my code
Protected Sub Button2_Click1(sender As Object, e As EventArgs) Handles Button2.Click
Dim sc As StringCollection = New StringCollection
Dim field1 As String = String.Empty
Dim i As Integer = 0
Do While (i < GridView1.Rows.Count)
field1 = GridView1.Rows(i).Cells(0).Text
i = (i + 1)
Loop
' get the field to be Inserted
sc.Add(field1)
' add the field to be Inserted in the StringCollection
InsertRecords(sc)
' call method for insert and pass the StringCollection values
End Sub
Dim conn As MySqlConnection = New MySqlConnection("Server=****************;Database=******;Uid=*******;Pwd=****;allow user variables=true")
Dim sb As StringBuilder = New StringBuilder(String.Empty)
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO student(name, age, adress) VALUES ("
sb.AppendFormat("{0}'{1}' ", sqlStatement, item)
Next
sb.Append(")")
MsgBox(sb.ToString)
Try
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand(sb.ToString, conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg = (msg + ex.Message)
Throw New Exception(msg)
Finally
conn.Close()
End Try
End Sub
Don't concatenate strings to create a sql command but use parameters to primarily avoid sql-injection.
Const sqlStatement As String = "INSERT INTO student(name, age, adress) VALUES (?Pname,?Page,?Padress)"
Try
Using con = New MySqlConnection(connectionString)
con.Open()
For Each item In sc
Using cmd = New MySqlCommand(sqlStatement, con)
cmd.Parameters.AddWithValue("?Pname", item.Name)
cmd.Parameters.AddWithValue("?Page", item.Page)
cmd.Parameters.AddWithValue("?Padress", item.Padress)
cmd.ExecuteNonQuery()
End Using
Next
End Using
Catch ex As System.Data.SqlClient.SqlException
' log message '
Throw ' don't use throw new Exception or throw ex '
End Try
Note that i've used sc like a collection of a custom class with all needed properties. But even if that was not correct, it should give you an idea how it works.