Just began using PostgresQL for a vb application (using visual studio 2005 pro) and connect via ODBC (there's a reason for using the ODBC connection and not the native PostgresQL connector) .
I'm used to using the #something and cmd.Parameters.Add("#something", data) format with MSSQL. I have 9 values i want to get from a form and use them in an insert statement but can't seem to figure the syntax for PostgresQL out.
Ideas? I've searched for two days trying to find an answer to this btw.
Edit: Sorry, I already deleted the code I was trying, but I kept getting "the column does not exist" error on column "name" which is my first paramater.
I know it's not a connection error or a naming convention issue or something like that because the following code does work. Here's how I'm doing it now for testing:
strSQL = "INSERT INTO tableb (name, extension, length,creationtime,lastaccesstime,lastwritetime,directoryname) VALUES ('Name','Extension','Length','CreationTime','LastAccessTime','LastWriteTime','DirectoryName')"
objConn.ConnectionString = strConnString
objConn.Open()
With objCmd
.Connection = objConn
.CommandText = strSQL
.CommandType = CommandType.Text
.ExecuteNonQuery()
End With
Oh, and the ODBC version I'm using is 8.03.02.00
More info:
The code causing the error:
strSQL = "INSERT INTO TABLEB (name) VALUES (#name)"
objConn.ConnectionString = strConnString
objConn.Open()
'Try
With objCmd
.Parameters.Add("#name", SqlDbType.Int)
.Parameters("#name").Value = "SomeText"
.Connection = objConn
.CommandText = strSQL
.CommandType = CommandType.Text
.ExecuteNonQuery()
End With
Code with parameters:
The exact error: ODBC Exception:
"ERROR [42703] ERROR: column "name" does not exist;
Error while executing the query"
The error occurs on the .ExecuteNonQuery
Thanks again!
problem is with below code
.Parameters.Add("#name", SqlDbType.Int)
.Parameters("#name").Value = "SomeText"
you set name as SqlDbType.Int but you set text value to it
give correct column type when declare the parameters and assign correct value which match with given data type.
And also give parameters as ? in sql statement and then add the command parameters in the same sequence given in the sql. ODBC do not support named parameters.
sample code :
strSQL = "INSERT INTO TABLEB (name) VALUES (?)"
objConn.ConnectionString = strConnString
objConn.Open()
With objCmd
.Parameters.AddWithValue("name", "SomeText")
.Connection = objConn
.CommandText = strSQL
.CommandType = CommandType.Text
.ExecuteNonQuery()
End With
As written that query is fine. Given the stated error, likely issues are:
Capitalization problems with quoting. If your column is defined as "Name" you need to refer to it as "Name" everywhere, not Name or name. See lexical structure.
Accessing the wrong database or an older version of the same database you set up and forgot, one that contains a tableb without a name column
In "anonymizing" the query you've hidden the real problem, or the error you quote doesn't match the code you're running. For example, quoting issues.
Are you sure the code you show is what you're getting the error from? You talk about #parameter etc in the text, but there's nothing like that in the code...
You should certainly be using parameterized queries instead of this approach to prevent SQL injection attacks, since I'm sure your real code doesn't hard code the values. Parameter use should be no different between psqlODBC and MS SQL Server's ODBC driver, that's half the point of query parameters. I don't speak Visual Basic (or ODBC if I can avoid it) and the SQL injection rosetta stone doesn't have details for VB.NET. Try doing what you do with MS SQL Server and if you have issues, follow up with a new question that includes the exact code and errors.
Related
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.
I have a SQL Server database with a table called tblFeatures with 2 columns Feature (Nvarchar(50)) and Setting (bit). I am trying to set the value of this Setting for each Feature via a check box in VB NET. I have tried using True/False 0/1 but have not had luck doing so using SQL parameters. I can do this fine using a normal SQL Update command:
"UPDATE tblSettings SET [Setting]='" & True & "' WHERE Feature='FSCreateTicket'"
However, I want to do it the proper/safe way with SQL parameters. I have scoured Stack and Google results have not found the proper way to get this done. I either get an error, or no error but the value does not get updated.
Here is what I have am currently trying:
Public Function ChangeSetting(ByVal strFeature As String, ByVal bSetting As Boolean)
Dim sqlcmd As New SqlCommand
Try
MYSQL.Open()
sqlcmd.Connection = MYSQL
sqlcmd.CommandText = "UPDATE tblSettings SET Setting='#setting' WHERE Feature='#feature'"
sqlcmd.Parameters.Add("#setting", SqlDbType.Bit).Value = bSetting
sqlcmd.Parameters.Add("#feature", SqlDbType.NVarChar, 50).Value = strFeature
sqlcmd.ExecuteNonQuery()
I am getting the error
Conversion failed when converting the varchar value '#setting' to data type bit
I don't understand why it says varchar when the variable sent is boolean and I have declared the SqlDbType as bit.
I have also tried using the AddwithValue parameter without luck.
Public Function ChangeSetting(ByVal strFeature As String, ByVal bSetting As Boolean)
Dim sqlcmd As New SqlCommand
Try
MYSQL.Open()
sqlcmd.Connection = MYSQL
sqlcmd.CommandText = "UPDATE tblSettings SET Setting='#setting' WHERE Feature='#feature'"
sqlcmd.Parameters.AddWithValue("#setting", bSetting)
sqlcmd.Parameters.Add("#feature", SqlDbType.NVarChar, 50).Value = strFeature
sqlcmd.ExecuteNonQuery()
This produces no error, but values are not updated. Please help!
Remove the single quotes a around the parameters in your query text, i.e. change
...
sqlcmd.CommandText = "UPDATE tblSettings SET Setting='#setting' WHERE Feature='#feature'"
...
to:
...
sqlcmd.CommandText = "UPDATE tblSettings SET Setting=#setting WHERE Feature=#feature"
...
When using parameterized queries, quotes will placed if needed you don't have to do it manually and you shouldn't.
I am new to this forum, please could you help me get this code to work, when i execute it, it simply does nothing and does not update the DB. If i remove the square brackets it gives an error: "SYNTAX ERROR in UPDATE statement"
Any help appreciated!
Dim connection As OleDbConnection
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserDB.accdb;Jet OLEDB:Database;")
connection.Open()
Dim pass As String
pass = txtconfirm.Text
Dim user As String
user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= '" & pass & "' WHERE [Username]= '" & user & "';"
Dim command As New OleDbCommand(query, connection)
command.ExecuteNonQuery()
connection.Close()
Given your actual connection string, the database that will be updated is the one in the directory where your application starts. This means that if you work with a WinForms application this folder is \BIN\DEBUG or x86 variant. If there is not error then you could get the return value of the ExecuteNonQuery call to verify if a record has been updated or not
Dim rowsUpdated = command.ExecuteNonQuery()
MessageBox.Show("Record updated count = " & rowsUpdated)
If this value is not zero then your database has been updated and you are looking for changes in the wrong database. Check the one in the BIN\DEBUG folder.
In any case your code has big problems. If your variables user or pass contain a single quote, then your code will crash again because your string concatenation will form an invalid SQL. As usual the only workaround is to use a parameterized query
Dim pass = txtconfirm.Text
Dim user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= #p1 WHERE [Username]= #p2"
Using connection = New OleDbConnection("...........")
Using command As New OleDbCommand(query, connection)
connection.Open()
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = pass
command.Parameters.Add("#p2", OleDbType.VarWChar).Value = user
command.ExecuteNonQuery()
End Using
End Using
The parameterized approach has many advantages. Your query text is more readable, there is no misunderstanding between your code and the values expected by your database engine. And while not easy to exploit with MS-Access there is no problem with Sql Injection
I think Steve presents a much better approach for you coding this...
Let me just throw out a few more things:
The reason you can't take those brackets out is some of your column names are reserved words; just FYI.
Since you report "it does nothing..." when you execute, it sounds like you have a valid connection and sql syntax, in which case my next step would be to copy the sql command text while in debug mode, change it to a select and run it in your DB. You should get one result when you do. If not, either your criteria or field contents are not what you think they are...
Just change the Update table SET field-value ... to SELECT * FROM table and leave the WHERE clause as is.
I'm writing small VB.Net app which should build reports based on data gathered from some external MDB-files (Access 2007). It was planned that this app will use parametrized SQL queries to collect data. One of the parameters for these queries is path to the external MDB-file.
Here goes sample code:
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=C:\Temp\Temp.mdb;")
conn.Open()
Dim cmd As New OleDbCommand()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT * INTO Trend FROM TI IN '?' WHERE TI.Id=?;"
With cmd.Parameters
.Add("#p1", OleDbType.VarChar).Value = "C:\Temp\Source.mdb"
.Add("#p2", OleDbType.Integer).Value = 5
End With
cmd.ExecuteNonQuery()
conn.Close()
Looks simple but it doesn't works. After launch my app throws following exception - System.Data.OleDb.OleDbException: Disk or network error.
Have spent a whole day to make it work with no success. What have I done wrong?
This is a comment that others have suggested is the answer to the question:
Nothing in an Access/Jet/ACE FROM clause is parameterizable (unless it's inside a subquery, of course).
With Access/Jet/ACE your only choice is to use some other method to write the FROM clause on-the-fly.
Dim NorthWindOledbConnection As String = "Provider=SQLOLEDB;DataSOurce=SARAN-PC\SQLEXPRESS;Integrated Security=ssp1;InitialCatalog=Sara"
Dim rs As New ADODB.Recordset()
rs.Open("select * from SecUserPassword", NorthWindOledbConnection, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockBatchOptimistic)
i tried to run this above code in visual studio 2008 - it shows the following error:
"Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done"
Firstly, don't use ADO in VB.NET. Use ADO.NET.
Other than that, create a proper Connection object instead of passing around a string.
And fix your connection string. It's SSPI, not SSP1. And it's Data Source, not DataSOurce. And it's Initial Catalog, not InitialCatalog.
You are using a very very very old way to access a Database that has been used with Visual Basic 6 and older.
Check to use ADO.NET instead of old ADO. For example you can use this code that is "similar" to the code you are using (but is not the best way to access the data on VS2008)
OleDbConnection con= New OleDbConnection( **Your Connection String** )
con.Open()
Dim command As OleDbCommand = New OleDbCommand("select * from SecUserPassword", con)
sqlCommand .CommandType = CommandType.Text
Dim reader As OleDbDataReader = TheCommand.ExecuteReader()
While reader.Read()
System.Console.Write(reader(** Your Table Field Name** ).ToString())
End While
con.Close()
To view how to create a correct connection String see the site http://www.connectionstrings.com/
If you want to access to an SQL Server database also you can use the SQLClient namespace instead the OleDb. For example System.Data.SqlClient.SqlConnection instead the OleDbConnection to provide better performance for SQL Server
The link below is an article that gives a great breakdown of the 6 scenarios this error message can occur:
Scenario 1 - Error occurs when trying to insert data into a database
Scenario 2 - Error occurs when trying to open an ADO connection
Scenario 3 - Error occurs inserting data into Access, where a fieldname has a space
Scenario 4 - Error occurs inserting data into Access, when using adLockBatchOptimistic
Scenario 5 - Error occurs inserting data into Access, when using Jet.OLEDB.3.51 or ODBC driver (not Jet.OLEDB.4.0)
Scenario 6 - Error occurs when using a Command object and Parameters
http://www.adopenstatic.com/faq/80040e21.asp
Hope it may help others that may be facing the same issue.