How can I fix the oledbexception: Undefined function 'convert' in expression? - sql

I am attempting to insert a single record into an SQL Server 2012 database, programmatically, using a small VB.net application. When I execute the application, the following OleDBException is caught:
Undefined function 'convert' in expression
My VB looks like this:
Dim conn As OleDbConnection = New OleDbConnection(connstring)
Dim comm As OleDbCommand = New OleDbCommand(insertcommand)
comm.Connection = conn
Try
conn.Open()
comm.ExecuteNonQuery()
Catch ex As Exception
txbErrorSummary.Text += ex.ToString()
End Try
Where insertcommand looks like:
INSERT INTO XXX([JCN], [DOT])
VALUES('PD7654',convert(varchar, '2/17/2014', 101))
Interestingly, when I cut and paste the insertcommand into the SQL Management Studio, it inserts the record with no trouble. Thoughts?
Appreciate the help

I will suggest you to do this other way. Instead of trying to run convert inside SQL, do this in .NET application and pass already DateTimem object.
The probelm with convert function is that it is not an OleDB valid function. If you use SqlCommand it will probably works correctly, because this function is T-SQL valid only for MS SQL

Related

Why does VB.Net throw an error when running an Access update query while it runs properly in Access

I am running an Access update query in VB.Net.
dbCustSpec_ADO.Execute("table_upt")
Ir runs fine except for the following "Update to" statement
[table].[field1] & [table].[field2]
The following is working properly
[table].[field1]
So does the following
[table].[field2]
It is only when I concatenate both fields when VB.Net throws an error:
System.Runtime.InteropServices.COMException: 'Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.'
Btw: The concatenation works properly when calling the query in Access.
My question is:
How can I concatenate both fields in order to make it run while calling it from VB.net
It not clear, are you using the .net oleDB provider here?
Or are you creating a instance of the Access database engine?
You better off to use oleDB such as this:
Imports System.Data.OleDb
And then your code to update can look like this:
Using conn As New OleDbConnection(My.Settings.TESTAce)
Dim strSQL As String = "UPDATE tblHotels SET FullName = FirstName + ', ' + LastName"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
cmdSQL.ExecuteNonQuery()
End Using
End Using
And if you wanted to ran a "existing" update query in Access?
They are considered store procedures. Say we have upate query saved in Access called
qryFirstLast
Then the above code to run that query would be:
Using conn As New OleDbConnection(My.Settings.TESTAce)
Dim strSQL As String = "qryFirstLast"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
cmdSQL.CommandType = CommandType.StoredProcedure
cmdSQL.ExecuteNonQuery()
End Using
End Using
Note how we set the command type = StoredProcedure.

havin issues inserting data into mysql using vb.net. it's keeps telling me connection already open [duplicate]

This error keeps popping up!!! An unhandled exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll
Additional information: The connection is already open.
Dim cmd As MySqlCommand
con.Open()
Try
cmd = con.CreateCommand()
cmd.CommandText = "update animal_sale set #NOAB,#Amount,#Tax,#Total where Species=#Species"
cmd.Parameters.AddWithValue("#Species", TextBoxSpecies.Text)
cmd.Parameters.AddWithValue("#NOAB", TextBoxNo.Text)
cmd.Parameters.AddWithValue("#Amount", TextBoxAmount.Text)
cmd.Parameters.AddWithValue("#Tax", TextBoxTax.Text)
cmd.Parameters.AddWithValue("#Total", TextBoxTotal.Text)
cmd.ExecuteNonQuery()
load()
Catch ex As Exception
End Try
End Sub
It looks like you are not closing the connection after executing the query. You only have
con.Open()
and are not closing the connection after
cmd.ExecuteNonQuery()
Keep your database objects local to the method where they are used. Then you always know the state of a connection and can be sure they are closed and disposed. Using...End Using blocks do this for you even if there is an error. In this code both the connection and the command are covered by a single Using block. Note the comma at the end of the first Using line.
You can pass your connection string directly to the constructor of the connection.
You can pass your command text and the connection directly to the constructor of the command.
You Update sql command is not correct. You need to tell the server what fields to update. I had to guess at the names of the fields. Check you database for the correct names and adjust the code accordingly.
Please don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Here is another
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
I had to guess at the datatypes and field size for the .Add method. Check you database for the correct values and adjust the code.
I converted the text box strings to the proper datatype here in the database code but normally these values would be parsed and converted before they reach this code.
Private Sub UpdateSale()
Using con As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand("update animal_sale set nonab = #NOAB, amount = #Amount, tax = #Tax, total = #Total where species = #Species;", con)
cmd.Parameters.Add("#Species", MySqlDbType.VarChar, 100).Value = TextBoxSpecies.Text
cmd.Parameters.Add("#NOAB", MySqlDbType.Int32).Value = CInt(TextBoxNo.Text)
cmd.Parameters.Add("#Amount", MySqlDbType.Decimal).Value = CDec(TextBoxAmount.Text)
cmd.Parameters.Add("#Tax", MySqlDbType.Decimal).Value = CDec(TextBoxTax.Text)
cmd.Parameters.Add("#Total", MySqlDbType.Decimal).Value = CDec(TextBoxTotal.Text)
con.Open
cmd.ExecuteNonQuery()
End Using
End Sub

SQL Sum showing statement instead of value on asp page

I'm trying to display the results of a simple SQL sum... I have the following SQL command on my .asp page using vb:
<%
Dim QtyTotal
QtyTotal = "SELECT SUM(Qty_SAL) FROM dbo.tbl_stock_at_locations"
Response.Write(QtyTotal)
%>
The output (QtyTotal) is written as the SQL statement itself and not the value.
Try adding something like this to connect to your database and to run your query.
Dim con As SqlConnection = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
Dim cmd As SqlCommand = New SqlCommand("SELECT SUM(Qty_SAL) FROM dbo.tbl_stock_at_locations", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
There are tons of articles out there on how to do this, please refer to google.com
You have this value:
"SELECT SUM(Qty_SAL) FROM dbo.tbl_stock_at_locations"
That's just a string literal. Nothing more. Assigning it to QtyTotal just means the variable is a string with the SQL command text as it's value.
If you want to run the statement and get the result, you need to create an ADO.Connection object to the connect to a database server, create an ADO.Command object to hold your SQL statement, and associate the command with the connection. Then you can .Open the connection and .Execute the command to get an object back for reading results... the kind of object will depend on how you execute the command. Once you have this object, you have to actually read from it to assign the final value to QtyTotal.

vb.net procedure or function expects parameter which was not supplied

This seems so simple, but I can't resolve the error
Procedure or function 'test' expects parameter '#id', which was not supplied.
I have tried a dataadapter instead of the reader, tried the {call test (?)} syntax, and several variants on how to add the parameter.
CREATE PROCEDURE [dbo].test (#id int)
AS
BEGIN
select * from tmptable where id=#id
END
Using conn = New OdbcConnection(connstring)
conn.Open()
Dim cmd As OdbcCommand = New OdbcCommand("test", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#id", 6)
Dim reader As OdbcDataReader = cmd.ExecuteReader()
reader.Close()
conn.Close()
End Using
Try dropping the # - so AddWithValue("id",6) instead. I usually explicitly create the parameter and add it to the collection, and when I do I drop the # sign from the parameter name.
Also, I'll modify your code to look like how I usually use it and edit it into my post in a few minutes, if dropping the # doesn't work you can try my style, maybe there are some subtle differences.
EDIT: Oops, my bad, I use the explicitly defined parameters with SQLcommands, not ODBC commands! You can try leaving out the #, but I don't have a working example I can share with you, sorry :-(
EDIT 2: OK, I don't have an example, but Microsoft has one that looks a lot more like how I call my stored procedures using SQLCommands, see
http://msdn.microsoft.com/en-us/library/system.data.odbc.odbcparametercollection%28v=vs.90%29.aspx
Basically, I think your code would look like
Using conn = New OdbcConnection(connstring)
conn.Open()
Dim cmd As OdbcCommand = New OdbcCommand("{ call test(?) }", conn)
cmd.CommandType = CommandType.StoredProcedure
' replace this with the following cmd.Parameters.AddWithValue("#id", 6) '
Dim ParamID As New OdbcParameter()
ParamID.DbType = DbType.Int32
ParamID.Value = 6
cmd.Parameters.Add(ParamID)
' end replace '
Dim reader As OdbcDataReader = cmd.ExecuteReader()
reader.Close()
conn.Close()
End Using
And you should also be aware that some ODBC drivers are not good at getting recordsets back from stored procedures. I use SmallTalk to query DB2 through ODBC, and I can get a recordset back from a function, but not from a stored procedure. You may be encountering a similar limitation. What database are you using?

Connection string to Oracle 10g DB using VB.net

Hey all i am VERY new to a Oracle DB and i am trying to connect to it via VB.net 2010. I have been trying the following:
Dim myConnection As OleDbConnection
Dim myCommand As OleDbCommand
Dim dr As OleDbDataReader
myConnection = New OleDbConnection("Provider=MSDAORA.1;UserID=xxxx;password=xxxx; database=xxxx")
'MSDORA is the provider when working with Oracle
Try
myConnection.Open()
'opening the connection
myCommand = New OleDbCommand("Select * from emp", myConnection)
'executing the command and assigning it to connection
dr = myCommand.ExecuteReader()
While dr.Read()
'reading from the datareader
MessageBox.Show("EmpNo" & dr(0))
MessageBox.Show("EName" & dr(1))
MessageBox.Show("Job" & dr(2))
MessageBox.Show("Mgr" & dr(3))
MessageBox.Show("HireDate" & dr(4))
'displaying data from the table
End While
dr.Close()
myConnection.Close()
Catch ee As Exception
End Try
And i get the error on the Catch ee As Exception line: ORA-12560: TNS:protocol adapter error
I also have a tnsnames.ora file on my computer but i am unsure if i need to use that when connecting (or really, how too in the first place)? Is it needed for the code above?
I am trying to use a DNS-Less connection to the DB. Not sure if that is what it is doing in this or not?
Any help would be great!!! :o)
David
There are many ways: the one I use almost every time that doesn't require an entry in TNSNAMES.ORA is this:
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;
And if you don't need an OleDb connection I think you should use System.Data.OracleClient or any other free provider (like DevArt dotConnect for Oracle Express)
Source: http://www.connectionstrings.com/oracle
I always use www.connectionstrings.com/ when I need to create a new connection string to the DB and when connection string format is not on top of my head.