I just begin with Oracle. I read lot of post and ... I don't find where is my mistake
I've a function in package PKG_GETOBJ
FUNCTION GetNewID(sReference IN VARCHAR2) RETURN NUMBER
IS
NewCtpVal NUMBER;
BEGIN
UPDATE TABLE set VALUE = (VALUE + 1) WHERE Field= sReference RETURN VALUE INTO NewCtpVal;
return NewCtpVal;
END;
and here how I try to call it:
Dim con As OracleConnection = GetConnexion()
con.Open()
Dim cmd As New OracleCommand With {.Connection = con}
'PKG_GETOBJ.GETNEWID('ID_OBJECT');'Sample calling in SQL with success
cmd.Parameters.Add(New OracleParameter With {.ParameterName = "sReference", .OracleDbType = OracleDbType.Varchar2, .Value = "ID_OBJECT", .Direction = ParameterDirection.Input})
cmd.Parameters.Add(New OracleParameter With {.ParameterName = "NewCtpVal", .OracleDbType = OracleDbType.Double, .Direction = ParameterDirection.ReturnValue})
cmd.CommandText = "PKG_GETOBJ.GETNEWID"
cmd.CommandType = CommandType.StoredProcedure
cmd.ExecuteNonQuery()
For Each p As OracleParameter In cmd.Parameters
HelperJournal.WriteEntry("PKG_GETOBJ " & p.ParameterName, If(p.Value Is Nothing, "null", p.Value.ToString))'Write in file
Next
con.Close()
con.Dispose()
My problem is NewCtpVal is empty, then I Database I've a number value...
Finnally I found a way...
Public Function GetNewId() As Decimal
Dim retval
Using con As OracleConnection = GetConnexion(),
cmd As New OracleCommand With {.Connection = con}
cmd.CommandText = "PKG_GETOBJ.GETNEWID"
cmd.CommandType = CommandType.StoredProcedure
Dim prm = New OracleParameter("returnvalue", OracleDbType.Decimal)
prm.Direction = ParameterDirection.ReturnValue
cmd.Parameters.Add(prm)
Dim prm1 = New OracleParameter("sReference", OracleDbType.Varchar2)
prm1.Direction = ParameterDirection.Input
prm1.Value = "ID_OBJECT"
cmd.Parameters.Add(prm1)
con.Open()
cmd.ExecuteNonQuery()
retval = cmd.Parameters("returnvalue").Value.ToString
End Using
Return retval
End Function
Related
Im getting this error while inserting data to my mdf database file
System.IndexOutOfRangeException: 'An SqlParameter with ParameterName '#qtysold' is not contained by this SqlParameterCollection.'
This is my code for order function
Function order(ByVal cart As List(Of Integer), ByVal product_qty As List(Of Integer))
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
'INSERT INTO PRODUCT TABLE
cmd.CommandType = CommandType.Text
cmd.CommandText = "UPDATE product SET product_qty= product_qty - #qty WHERE product_id= #id"
cmd.Parameters.Add("#qty", SqlDbType.Int)
cmd.Parameters.Add("#id", SqlDbType.Int)
For i As Integer = 0 To cart.Count - 1
cmd.Parameters("#id").Value = cart(i)
cmd.Parameters("#qty").Value = product_qty(i)
cmd.ExecuteNonQuery()
Next
'INSERT INTO SALES TABLE
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO sales VALUES (#id, #productname, #qtysold, #date)"
cmd.Parameters.Add("#id", SqlDbType.Int)
cmd.Parameters.Add("#productname", SqlDbType.VarChar)
cmd.Parameters.Add("#qtysold", SqlDbType.Int)
cmd.Parameters.Add("#date", SqlDbType.Date)
For i As Integer = 0 To cart.Count - 1
cmd.Parameters("#id").Value = cart(i)
cmd.Parameters("#productname").Value = getName(cart(i))
cmd.Parameters("#qtysold").Value = product_qty(i)
cmd.Parameters("#date").Value = datefield.Text
cmd.ExecuteNonQuery()
Next
cart.Clear()
product_qty.Clear()
refresh()
End Function
THE ERROR HAPPENS HERE
cmd.Parameters("#qtysold").Value = product_qty(i)
That seems an odd exception in that situation as the code looks OK to me but it's wrong even if it did work. Don't add the parameters and then get them back by name over and over. The Add method you're calling returns the SqlParameter object added so assign it to a variable and then use that:
Dim idParameter = cmd.Parameters.Add("#id", SqlDbType.Int)
Dim productionNameParameter = cmd.Parameters.Add("#productname", SqlDbType.VarChar)
Dim qtySoldParameter = cmd.Parameters.Add("#qtysold", SqlDbType.Int)
Dim dateParameter = cmd.Parameters.Add("#date", SqlDbType.Date)
For i As Integer = 0 To cart.Count - 1
idParameter.Value = cart(i)
productionNameParameter.Value = getName(cart(i))
qtySoldParameter.Value = product_qty(i)
dateParameter.Value = datefield.Text
cmd.ExecuteNonQuery()
Next
NEVER use the same complex expression over and over. ALWAYS use it once and assign the result to a variable, then use that variable over and over. In this case, you don't even have to use the complex expression once, because you already had the object but just ignored it.
i have a webservice that inserts, delete, updates the data from or to a database. so in this particular form it has a foreign key. so basically it should only accept values which are present in the primarty table.
when user enters any other value a exception occurs.
How do I make sure that such type of SQL exception when caught, a user friendly custom error message(Such as the entered ID doesn't exist.Data insertion failed!) is passed from my web service.
Thanks a lot.
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()>
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")>
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
<ToolboxItem(False)>
Public Class WebService2
Inherits System.Web.Services.WebService
Public Class Details
Public Property CardID As Integer
Public Property BookID As Integer
Public Property IssuedBy As String
End Class
<WebMethod>
Public Sub AddBook(ByVal emp As Details)
Dim cs1 As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con1 As SqlConnection = New SqlConnection(cs1)
Dim thequery As String = "select * from BookIssue where CardID=#CardID"
Dim cmd1 As SqlCommand = New SqlCommand(thequery, con1)
cmd1.Parameters.Add(New SqlParameter() With {
.ParameterName = "#CardID",
.Value = emp.CardID
})
con1.Open()
Dim reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
MsgBox("ID Number is Already in use")
con1.Close()
Else
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("spInsertIntoBookIssue", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#CardID",
.Value = emp.CardID
})
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#BookID",
.Value = emp.BookID
})
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#IssuedBy",
.Value = emp.IssuedBy
})
con.Open()
cmd.ExecuteNonQuery()
MsgBox("Data Inserted")
End Using
End If
End Using
End Sub
<WebMethod>
Public Sub GetAllDetails()
Dim listEmployees As List(Of Details) = New List(Of Details)()
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("Select * from BookIssue", con)
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Dim details As Details = New Details()
details.CardID = Convert.ToInt32(rdr("CardID"))
details.BookID = Convert.ToInt32(rdr("BookID"))
details.IssuedBy = rdr("IssuedBy").ToString()
listEmployees.Add(details)
End While
End Using
Dim js As JavaScriptSerializer = New JavaScriptSerializer()
Context.Response.Write(js.Serialize(listEmployees))
End Sub
<WebMethod>
Public Sub GetAllDetails1()
Dim listEmployees As List(Of Details) = New List(Of Details)()
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("Select * from BookIssue", con)
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Dim details As Details = New Details()
details.CardID = Convert.ToInt32(rdr("CardID"))
details.BookID = Convert.ToInt32(rdr("BookID"))
details.IssuedBy = rdr("IssuedBy").ToString()
listEmployees.Add(details)
End While
End Using
Dim js As JavaScriptSerializer = New JavaScriptSerializer()
Context.Response.Write(js.Serialize(listEmployees))
End Sub
<WebMethod>
Public Function GetdetailsById(ByVal CardID As Integer) As Details
Dim details As Details = New Details()
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("spGetBookIssueDetailsByCardID", con)
cmd.CommandType = CommandType.StoredProcedure
Dim parameter As SqlParameter = New SqlParameter()
parameter.ParameterName = "#CardID"
parameter.Value = CardID
cmd.Parameters.Add(parameter)
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
details.CardID = Convert.ToInt32(rdr("CardID"))
details.BookID = Convert.ToInt32(rdr("BookID"))
details.IssuedBy = rdr("IssuedBy").ToString()
End While
End Using
Return details
End Function
<WebMethod>
Public Function GetdetailsById1(ByVal CardID As Integer) As Details
Dim details As Details = New Details()
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("spGetBookIssueDetailsByCardID1", con)
cmd.CommandType = CommandType.StoredProcedure
Dim parameter As SqlParameter = New SqlParameter()
parameter.ParameterName = "#CardID"
parameter.Value = CardID
cmd.Parameters.Add(parameter)
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
details.CardID = Convert.ToInt32(rdr("CardID"))
details.BookID = Convert.ToInt32(rdr("BookID"))
details.IssuedBy = rdr("IssuedBy").ToString()
End While
End Using
Return details
End Function
<WebMethod>
Public Sub DeleteRecord1(ByVal emp As Details)
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("spDeleteByID", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#CardID",
.Value = emp.CardID
})
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
<WebMethod>
Public Sub Update(ByVal emp As Details)
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("spUpdateBookIssue", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#CardID",
.Value = emp.CardID
})
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#BookID",
.Value = emp.BookID
})
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#IssuedBy",
.Value = emp.IssuedBy
})
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
End Class
I suggest modeling your code off this example, i modified the delete sub you provided to include a catch with a custom ErrorRoutine for unhandled cases, otherwise you can obtain the number of deleted rows from the executeNonQuery() function. I also chnaged so we return the number of deleted rows, this way if its less than 1 you can do whatever you want with messages after calling the delete.
Public Sub DeleteRecord1(ByVal emp As Details) As Integer
Dim cs As String = ConfigurationManager.ConnectionStrings("library management
systemConnectionString").ConnectionString
Dim m_RowsDeleted As Integer
Dim con As SqlConnection = New SqlConnection(cs)
Try
Using con
Dim cmd As SqlCommand = New SqlCommand("spDeleteByID", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#CardID",
.Value = emp.CardID
})
con.Open()
m_RowsDeleted = cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
ErrorRoutine(ex, "Delete")
Finally
If Not IsNothing(con) Then
If con.State = ConnectionState.Open Then
con.Close()
End If
End If
End Try
Return m_RowsDeleted
End Sub
I have a function that calls a stored procedure. I need to compare the result to an input parameter. I keep getting a warning that the function does not return on all code paths, but I can't figure out where.
So, 2 questions:
1. Am I looping through the SqlDataReader correctly or should I fill a datatable with my reader results?
2. Where am I missing a return value?
Function code:
Function FZCheck(FZ As String) As Boolean
Dim constr As String = My.Settings.devTOD.ToString
Dim con As New SqlConnection(constr)
Dim cmd As New SqlCommand("spSelectFloodZones", con)
cmd.CommandType = CommandType.StoredProcedure
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim rdr As SqlDataReader
rdr = cmd.ExecuteReader
If rdr.HasRows Then
Do While rdr.Read
If String.Equals(rdr(0).ToString, FZ) = True Then
Return True
Else
Return False
End If
Loop
Else
Return False
End If
If con.State = ConnectionState.Open Then
con.Close()
End If
rdr.Close()
End Function
Stored proc code: (very simple)
ALTER PROCEDURE [dbo].[spSelectFloodZones]
AS
SET NOCOUNT ON
SET ROWCOUNT 0
-- ====================
-- Select flood zones
-- ====================
SELECT DISTINCT FloodZone
FROM TOD.dbo.FloodZones
Language is VB.NET, using SQL Server 2012.
Here you go with some minor refactoring.
Function FZCheck(FZ As String) As Boolean
Dim constr As String = My.Settings.devTOD.ToString
Dim con As New SqlConnection(constr)
Dim result As Boolean = False
Dim cmd As New SqlCommand("spSelectFloodZones", con)
cmd.CommandType = CommandType.StoredProcedure
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim rdr As SqlDataReader
rdr = cmd.ExecuteReader
If rdr.HasRows Then
Do While rdr.Read
If String.Equals(rdr(0).ToString, FZ) = True Then
result = True
End If
Loop
End If
If con.State = ConnectionState.Open Then
con.Close()
End If
rdr.Close()
Return result
End Function
I have installed Oracle 10g Express Edition database on a server and install the client on my PC.
Now, I`m developing a vb.net application using visual studio 2005 and I need to use the oracle 10g express edition database. So I initialize the connection using the following connection string:
_connectionString = "User Id=Graphya;Password=Graphya;Data Source=gis64:1522/XE;"
Then I define new OracleDataAdapter, and I use the following code to fill a dataset:
Dim insertCommand As OracleCommand = New OracleCommand()
Dim commandTextTemplate As String = "INSERT INTO {0}(" & g_pfldUsername & ", " & g_pfldSubject & ") VALUES (?, ?)"
insertCommand.CommandText = String.Format(commandTextTemplate,TABLE_NAME)
insertCommand.Connection = Me.Connection
insertCommand.Parameters.Add(New Oracle.DataAccess.Client.OracleParameter(g_pfldUsername, Oracle.DataAccess.Client.OracleDbType.Varchar2, 50, g_pfldUsername))
insertCommand.Parameters.Add(New Oracle.DataAccess.Client.OracleParameter(g_pfldSubject, Oracle.DataAccess.Client.OracleDbType.Varchar2, 50, g_pfldSubject))
_OracleDataAdapter.InsertCommand = insertCommand
_OracleDataAdapter.Fill(_dataSet, TABLE_NAME)
So after debugging this code I got the following error:
Unable to cast object of type 'Oracle.DataAccess.Client.OracleCommand' to type 'System.Data.Common.DbCommand'.
#Davideg: my code is c# to fill data set
OleDbConnection cnOra = new OleDbConnection("Provider=MSDAORA;Data Source=myOracleServer;"
+ "user id=myUID;password=myPWD;"
+ "persist security info=false;");
OleDbCommand cmdPerson = new OleDbCommand
+ ("{call PackPerson.allPerson({resultset 3, ssn, fname, lname})}", cnOra);
OleDbDataAdapter daPerson = new OleDbDataAdapter(cmdPerson);
cnOra.Open();
DataSet ds = new DataSet();
daPerson.Fill(ds,"Person");
this.dataGrid1.DataSource = ds.Tables["Person"];
cnOra.Close();
Function GetEmailsByPageName(ByVal pageName As String) As DataSet
Dim cn As New OracleConnection
Dim cmd As New OracleCommand
cn = New OracleConnection
cn.ConnectionString = (ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
cmd = New OracleCommand("ORACLEDBA.PACKAGE_EMAIL.SP_EMAIL_LISTING_BY_NAME")
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Connection = cn
cmd.BindByName = True
Dim paramCursor As OracleParameter = New OracleParameter("email_list_cursor", OracleDbType.RefCursor)
With cmd.Parameters
.Add(New OracleParameter("a_page_name", OracleDbType.Varchar2)).Value = pageName
.Add("a_err_code", OracleDbType.Int32, Data.ParameterDirection.Output)
.Add("a_err_msg", OracleDbType.Varchar2, 300).Direction = Data.ParameterDirection.Output
.Add(paramCursor).Direction = Data.ParameterDirection.Output
End With
Dim da As New OracleDataAdapter(cmd)
Dim dsEmail As DataSet = New DataSet
Try
da.SelectCommand = cmd
da.Fill(dsEmail)
Return dsEmail
Catch ex As Exception
Throw
Finally
da.Dispose()
cmd.Dispose()
cn.Dispose()
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
End Function
Dim objconn As New System.Data.SqlClient.SqlConnection(sConnStr)
Dim objcmd As New System.Data.SqlClient.SqlCommand(sSpName, objconn)
Try
objcmd.CommandType = CommandType.StoredProcedure
objcmd.Parameters.Add(prmId)
objconn.Open()
Dim myReader As SqlDataReader
If objconn.State = ConnectionState.Open Then
myReader = objcmd.ExecuteReader()
'myReader = objcmd.ExecuteReader()
If myReader.HasRows Then
If myReader.Read() Then
myFile = New File(myReader)
End If
End If
End If
Can Any one suggest me. what would be wrong in the above code. ExecuteReader is throwing excepion. Invalid cast from string to GUID. But My Sqlparamter was already uniqueidentifier nothing cast. Any Idea?
CREATE PROCEDURE GetFileInfo
#Id uniqueidentifier
AS
BEGIN
SELECT Id, DI_ID, sFileName, ContentType FROM FilesUpload Where Id=#Id
The value in your variable prmId is not a GUID, or rather, needs to be specified as such.
Using conn As New SqlClient.SqlConnection("YourConnectionString")
Using cmd As SqlClient.SqlCommand = conn.CreateCommand()
cmd.CommandText = "GetFileInfo"
cmd.Parameters.Add("#Id", SqlDbType.UniqueIdentifier)
cmd.Parameters("#Id").Value = New Guid(prmId)
conn.Open()
Dim myReader As SqlDataReader = cmd.ExecuteReader()
If myReader.Read() Then
myFile = New File(myReader)
End If
End Using
End Using