I'm getting the error System.Data.OleDb.OleDbException: 'Parameter #client_address has no default value.' but I have sent all the parameters needed.
cmd.Connection = cn
cmd.CommandText = "insert into invoice([invoice_date],[client_name],[client_company_name],[client_email],[client_contact_no],[client_address],[client_delivery_address],[total_basic_amount],[freight_rate],[delivery_rate],[advanced_amount],[pending_amount])
Values(#invoice_date,#client_name,#client_company_name,#client_email,#client_contact_no,#client_address,#client_delivery_address,#total_basic_amount,#freight_rate,#delivery_rate,#advanced_amount,#pending_amount)"
cmd.Parameters.AddWithValue("#invoice_date", datetime.Value)
cmd.Parameters.AddWithValue("#client_name", client_name.Text)
cmd.Parameters.AddWithValue("#client_company_name", company_name.Text)
cmd.Parameters.AddWithValue("#client_email", email.Text)
cmd.Parameters.AddWithValue("#client_contact_no", contact_no.Text)
cmd.Parameters.AddWithValue("#client_address", address.Text)
cmd.Parameters.AddWithValue("#client_delivery_address", delivery_address.Text)
cmd.Parameters.AddWithValue("#total_basic_amount", total_basic_amount.Text)
cmd.Parameters.AddWithValue("#freight_rate", freigh_rate.Text)
cmd.Parameters.AddWithValue("#delivery_rate", delivery_rate.Text)
cmd.Parameters.AddWithValue("#advanced_amount", advance_received_amount.Text)
cmd.Parameters.AddWithValue("#pending_amount", total_pending_amount.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Invoice Stored")
I'm using accessdb in vb.net. and all variables has value nothing is empty. when I comment or remove client_address it start giving error on client_delivery_address.
Changes the way to create the parameter specifying the type and size, as in the example below:
cmd.Parameters.Add("#client_address", System.Data.OleDb.OleDbType.BSTR, 100);
Related
I've recently started learning .net and I wrote a basic sql connected data entry form. Almost all of my data types are integer or decimals. Sometimes I need to remain empty the textboxes and enter "NULL" data and I receive with this error "Input string was not in correct format".
How I can fix this error ? Key point; I don't want to enter "0" it must be "NULL" in sql server because I use some charts to track all of these data, so when there is data equal the "0" its ruined my charts. As far as I understand from my researches Tryparse is fit for it but I couldn't find any information to use it properly in .net.
I'll share my transformation code below.
Try
Dim command As New SqlCommand()
command.Parameters.Add("A", SqlDbType.Decimal).Value = Decimal.Parse(A)
command.Parameters.Add("B", SqlDbType.Int).Value = Integer.Parse(B)
command.Parameters.Add("C", SqlDbType.Decimal).Value = Decimal.Parse(C)
command.Parameters.Add("D", SqlDbType.Decimal).Value = Decimal.Parse(D)
command.Parameters.Add("E", SqlDbType.Decimal).Value = Decimal.Parse(E)
command.Parameters.Add("F", SqlDbType.Decimal).Value = Decimal.Parse(F)
command.Parameters.Add("G", SqlDbType.Int).Value = Integer.Parse(G)
command.Parameters.Add("H", SqlDbType.Int).Value = Integer.Parse(H)
c.CUD(command, sql)
list()
clear()
MessageBox.Show("Data Successfully Saved")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
command.Parameters.Add("strokeTB", SqlDbType.Decimal).Value = If(strokeTB.TextLength = 0, CObj(DBNull.Value), Decimal.Parse(strokeTB.Text))
This assumes that you have already validated the contents of the TextBox and it is guaranteed to either be empty or contain a valid Decimal value.
This If operator is similar to the old IIf function but it's better because it short-circuits, i.e. the third argument operand is only evaluated if the first operand is False. Because IIf is a function, it evaluates all three arguments first, so Decimal.Parse would still be called and it would fail. Using If, Decimal.Parse will only be called if there is text to parse.
I do not understand why it's not inserting to my database whenever I include an apostrophe in my txtParticulars.Text and txtPayTo.Text.
The error is this:Syntax error (missing operator) in query expression ''Joy's Boutique','Top's,'Issued')'.
My textbox values are:
txtPayTo.Text > Joy's Boutique
txtParticulars > Top's
cmbRemarks.SelectedItem > Issued
But whenever my txtParticulars and txtPayTo values does not have an apostrophe, my data saves.
The following is my code:
sql1 = "INSERT INTO Table1(Check_No,Voucher_No,Issue_Date,Company_Name,Bank_Type,Amount_in_Figure,Amount_in_Words,Payee,Particulars,Remarks) VALUES(#CheckNo,#VoucherNo,#Date,#CompName,#BankType,#AmtInFigure,#AmtInWords,#PayTo,#Particulars,#Remarks)"
Dim cmd1 As OleDbCommand = New OleDbCommand(sql1, myConnection)
cmd1.Parameters.AddWithValue("#CheckNo", txtCheckNo.Text)
cmd1.Parameters.AddWithValue("#VoucherNo", txtVoucherNo.Text)
cmd1.Parameters.AddWithValue("#Date", dtpDate.Text)
cmd1.Parameters.AddWithValue("#CompName", txtCompName.Text)
cmd1.Parameters.AddWithValue("#BankType", txtBankType.Text)
cmd1.Parameters.AddWithValue("#AmtInFigure", txtAmtInFigure.Text)
cmd1.Parameters.AddWithValue("#AmtInWords", txtAmtInWords.Text)
cmd1.Parameters.AddWithValue("#PayTo", txtPayTo.Text)
cmd1.Parameters.AddWithValue("#Particulars", txtParticulars.Text)
cmd1.Parameters.AddWithValue("#Remarks", cmbRemarks.SelectedItem)
cmd1.ExecuteNonQuery()
Use Add instead of AddWithValue.
The latter has to guess the correct database type by the value passed in.
The Add method is more reliant on that (as long as you donĀ“t use the Add(string, object) overload).
Based on your example:
cmd1.Parameters.Add("#PayTo", SqlDbType.Varchar)
cmd1.Parameters("#PayTo").Value = txtPayTo.Text
or as one line (thanks to Plutonix):
cmd1.Parameters.Add("#PayTo", SqlDbType.Varchar).Value = txtPayTo.Text
I've been trying to figure out this bug for a while now, some help would be appreciated. Thanks.
Here is my error message:
Procedure or function 'getAvailableSMSNumbers' expects parameter '#Election_ID', which was not supplied.
Here is my sql code:
CREATE PROCEDURE {databaseOwner}{objectQualifier}getAvailableSMSNumbers
#Election_ID nvarchar(20)
AS
SELECT *
FROM {databaseOwner}{objectQualifier}icc_sms_phones
LEFT JOIN {databaseOwner}{objectQualifier}icc_sms_elections ON sms_elections_sms_number = phones_number
WHERE sms_elections_sms_number IS NULL
OR sms_elections_id = #Election_ID
GO
Function:
Public Overrides Function getAvailableSMSNumbers(eventid As String) As IDataReader
Dim dtable As New DataTable
Using sqlconn As New SqlConnection(Me.ConnectionString)
Using sqlcomm As New SqlCommand
Using sqlda As New SqlDataAdapter
sqlcomm.Connection = sqlconn
sqlcomm.CommandType = CommandType.StoredProcedure sqlcomm.CommandText=GetFullyQualifiedName("getAvailableSMSNumbers")
sqlcomm.Parameters.AddWithValue("#Election_ID", eventid)
sqlda.SelectCommand = sqlcomm
sqlconn.Open()
sqlda.Fill(dtable)
sqlconn.Close()
Return dtable.CreateDataReader
End Using
End Using
End Using
End Function
Where the function is used:
Public Function getAvailableSMSNumbers(eventid As String) As List(Of phoneModel)
Dim numbers As New List(Of phoneModel)
Dim number As phoneModel
numbers = CBO.FillCollection(Of phoneModel)(dal.getAvailableSMSNumbers(eventid))
For Each number In numbers 'dal.getAvailableSMSNumbers(eventid).Rows
number = New phoneModel
With number
.val = ("PHONES_NUMBER").ToString
.text = String.Format("{0:# (###) ###-####}", Long.Parse(.val))
End With
numbers.Add(number)
Next
Return numbers
End Function
If you need anymore information, let me know, and I will add it.
This typically occurs if the object supplied as the value of your SQL parameter is NULL, but the stored procedure does not allow null values (which yours does not). You can set a conditional breakpoint on this line sqlcomm.Parameters.AddWithValue("#Election_ID", eventid) to make sure the eventid parameter is not null.
It might also be a good idea to use defensive coding, and in your getAvailableSMSNumbers function, check to make sure eventid is not null, and if it is, throw an exception or provide some type of feedback for the user.
As an option you can try to re-compile your stored procedure to allow NULL parameter :
CREATE PROCEDURE {databaseOwner}{objectQualifier}getAvailableSMSNumbers
#Election_ID nvarchar(20) = NULL
AS
That means that the default value of your Parameter will be null in case there is no value on input. This solution will be nice in case you want to return empty datatable without error. In any other case you have to debug your VB code and understand where the issue starts.
Think about how you are calling you procedure. When you call you need to supply the value of the procedure: For example,
Call get_particular_girl_from_girlsTable("Jane")
where get_particular_girl_from_girlsTable is the procedure and "Jane" is value for parameter GirlName.
Did you verify if
cmd.CommandType = CommandType.**StoredProcedure**
By default, the value is Text, expecting a SELECT, INSERT or other command text.
When I'm calling a function from a PL/SQL package, there is a IN optional parameter (Date) with default value of SYSDATE.
When I execute my commmand, I don't have a choice but to add the parameter. Even if there is no value set, the function always receive null as the entered value, so it never affects the default value.
Dim cmd As New OracleCommand(con)
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "PACK.RefreshData"
Dim param1 As New OracleParameter()
param1.Direction = ParameterDirection.Input
param1.ParameterName = "p_date"
param1.DbType = DbType.Date
cmd.Parameters.Add(param1)
param1 = New OracleParameter()
param1.Direction = ParameterDirection.Output
param1.ParameterName = "po_errorCode"
param1.DbType = DbType.String
cmd.Parameters.Add(param1)
param1 = New OracleParameter()
param1.Direction = ParameterDirection.Output
param1.ParameterName = "po_errorDescription"
param1.DbType = DbType.String
cmd.Parameters.Add(param1)
con.Open()
cmd.ExecuteNonQuery()
In another question, somebody said the command property BindByName set to true works only for regular queries, not storedProcs. So what can I do to call the function without passing a value with my IN parameter?
Here is the Stored Proc header
Procedure RefreshData
(
p_date IN DATE := SYSDATE,
po_errorCode OUT varchar2,
po_errorDescription OUT varchar2
);
N.B. : I'm using Oracle.DataAccess.dll version 4.112.4.0
UPDATE : Here is the explanation taken from the oracle thread, from my answer below :
I think what it boils down to is that DervieParameters is deriving parameters for all of the proc params, even though they have default values, and that seems to me to be the correct behavior. Once you have parameters in the collection, if you don't assign a value to them, null will be passed.
What you probably need to do is
1) the best option, is not to use deriveparameters in the first place, and manually build the parameters collection, adding parameters for only the things you don't want to have default values:
DeriveParameters incurs a database round-trip and should only be used during design time. To avoid unnecessary database round-trips in a production environment, the DeriveParameters method itself should be replaced with the explicit parameter settings that were returned by the DeriveParameters method at design time.
2) If you want to continue using DeriveParameters, remove the unwanted parameters from the OracleParameters collection.
If you have default-value parameter not at the tail of the parameters chain you should perform named parameters call to avoid passing this default-value parameter. I think your data provider doesn't support this call type, so you should wrap your call in anonymous pl\sql block like this :
begin
PACK.RefreshData(po_errorCode => :po_errorCode, po_errorDescription=>:po_errorDescription);
end;
and then do what did before in VB code (ofcourse you CommandType will be Text).
Another solution is to move your default-value parameter to the end of parameters chain like this:
Procedure RefreshData
(
po_errorCode OUT varchar2,
po_errorDescription OUT varchar2,
p_date IN DATE := SYSDATE
);
Finally I have been able to find a way to call the procedure with this thread :
https://community.oracle.com/thread/2248928?tstart=0
Here is my corrected code :
con.Open()
cmd = con.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Pack.RefreshData"
cmd.BindByName = True
OracleCommandBuilder.DeriveParameters(cmd)
cmd.Parameters.RemoveAt(0) 'I remove the optional parameter
cmd.ExecuteNonQuery()
Then I retreive my OUT parameters
Dim outPrm1 as String = ""
If cmd.Parameters("po_errorDescription").Value IsNot Nothing Then
outPrm1 = cmd.Parameters("po_errorDescription").Value
End If
Trying to import records from an Access database file and display the records in a listview (in Visual Basic). It works 50% of the time, but seems to crash stating:
An unhandled exception of type 'System.Reflection.AmbiguousMatchException' occurred in Microsoft.VisualBasic.dll
Additional information: Overload resolution failed because no Public 'Add' can be called with these arguments:
'Public Overrides Function Add(text As String) As System.Windows.Forms.ListViewItem':
Argument matching parameter 'text' cannot convert from 'DBNull' to 'String'.
'Public Overrides Function Add(value As System.Windows.Forms.ListViewItem) As System.Windows.Forms.ListViewItem':
Argument matching parameter 'value' cannot convert from 'DBNull' to 'ListViewItem'.
The code in question is the following:
ds.Clear()
LVResults.Items.Clear()
con.ConnectionString = dbProvider & dbSource
con.Open() 'Open connection to the database
sqlstatement = "SELECT * FROM records WHERE checkoutdate is NULL"
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "allmembers") 'Fill the data adapter
con.Close()
Dim recordCount, x As Short
recordCount = 0
x = 0
recordCount = ds.Tables("allmembers").Rows.Count
With ds.Tables("allmembers")
Do Until x = recordCount
LVResults.Items.Add(.Rows(x).Item(0))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(1))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(2))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(3))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(4))
x = x + 1
Loop
End With
Knowing me it's something really obvious but do appreciate the help :)
The most annoying this is that it works sometimes, but others it'll throw up the error.
The error message is pretty self-explanatory to be honest - some of the fields contain null values, which VB won't auto-convert to empty strings or zeros. One solution would be to edit the SQL statement to explicitly avoid returning nulls:
SELECT IIf(Surname Is Null, '', Surname), IIf(Forename Is Null, '', Forename),
IIf(SomeIntField Is Null, 0, SomeIntField) FROM records WHERE CheckoutDate Is Null