Syntax error in table-level validation expression in MS ACCESS - c#

OleDbCommand oleDbCmd = new OleDbCommand();
OleDbConnection bookConn = Sqlhelper.Conncect_Mdb();
oleDbCmd.Connection = bookConn;
oleDbCmd.CommandText = "ALTER TABLE doc_comp ADD COLUMN versioncode NUMBER DEFAULT 0";
oleDbCmd.ExecuteNonQuery();
bookConn.Close();
Here is my code for alter table in ms access,it throws error Syntax error in table-level validation expression.This code works fine for without adding 'DEFAULT 0'. I am using MS ACCESS 2007.Tried with this but I cant set using tools.

Your code works for me if I use the following connect string:
static public OleDbConnection Conncect_Mdb()
{
const string oledb = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=scratch.accdb";
var conn = new OleDbConnection(oledb);
conn.Open();
return conn;
}
There are older drivers, specially the ones that run over ODBC that require you to indicate which sql support you need in the driver. An example of such seting in an Odbc connectionstring is ExtendedAnsiSQL=1.
If your setup doesn't have the Microsoft Access Database Engine 2010, which also support Access 2007, you can download and install the redistributable from the Microsoft Download.

This answer does not pertain to the specific question, but it does answer EXACTLY for the error message posted in the TITLE....
Syntax error in table-level validation expression in MS ACCESS
I received this exact error and the fix was to remove a semi colon from the end of the query statement.
I am using the OP's query to present the solution...
oleDbCmd.CommandText = "ALTER TABLE doc_comp ADD COLUMN versioncode NUMBER DEFAULT 0**;**";
Should be,
oleDbCmd.CommandText = "ALTER TABLE doc_comp ADD COLUMN versioncode NUMBER DEFAULT 0";
Remove the semi colon surrounded by asterisks from the query statement. This resolved this EXACT error for me.

Related

Moving Database from Sybase to SQL Server: ODBC not recognised named parameters

I'm updating an old project, moving its data source from Sybase to SQL Server. The data structures are identical (they're both copies of a commercial database - the Sybase version has been discontinued).
Because it's pretty old, it uses ODBC to connect. The connection strings originally specified a DSN. I've managed to connect to the SQL Server using both a raw connection string and a replacement DSN.
It executes code against the database by pulling command text from a config file and adding named parameters, like so:
var args = new Dictionary<string, object>()
{
{ "#myFirstParam", "myFirstValue" },
{ "#mySecondParam", "mySecondValue" }
}
IDbCommand cmd = Connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = Command.Timeout;
cmd.CreateParameters(Command.Parameters, args);
cmd.CommandText = [fetched from config]
IDataReader reader = null;
reader = cmd.ExecuteReader();
This all used to work fine with Sybase.
However, when I run it against SQL, when the reader executes I get the following error:
ERROR [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Must declare the scalar variable "#myFirstVariable".
I get this error whether I specify the connection as a DSN or a raw string. Stepping through the code, the parameter is certainly declared and has a valid value.
Reading up around this, it appears that this behaviour is to be expected. The Microsoft Documentation on ODBC connection says you can only use named parameters if you're calling a stored procedure, which I am not. Apparently the correct method is to put "?" characters in the command text and ODBC will insert the parameters by index.
If this is correct, I have no idea how this code ever worked with Sybase. I have another project which uses the same code for data loading, specifying named parameters and passing them into SQL command specified in config, but it's pointing at a different SQL Server database.
I presume this may be something to do with the configuration of the database, but I'm pretty lost on what to try from here. Any suggestions would be greatly appreciated.

How to get Visual Studio 2015 to work with Access 2010 LIKE wildcards

I'm working with an existing Access 2010 database that contains tables and queries ('views').
When I connect the database from Visual Studio 2015, tools like the Database Explorer can see the contents of the Access tables, but for queries that contain LIKE operators with '*' wildcards, it sees just the header titles, with zero records.
I found that if I duplicate those Access-based queries in Visual Studio but replace the LIKE '*' wildcards with '%', those VS-based queries work (they return non-zero records).
This particular Access database is full of queries with '*' and it would be difficult to change them all (eg., to ALIKE).
Is there a way to get Visual Studio tools to work with the '*' in LIKE queries in that database? Perhaps a parameter on the connection string, or a property in VS? Or maybe there is something that can be changed in the database itself (a global parameter)?
Changing the Provider in VS from Microsoft.ACE.OLEDB.4.0 to Microsoft.ACE.OLEDB.12.0 had no effect. The database is apparently 04.00.0000 (Connection properties).
My hope is to create a C# desktop app that can access that database (and its queries that have those '*' wildcards).
For background on the wildcard incompatibility, see for example LIKE query on an Access database via C# always returns COUNT(*) of 0
Thanks for any ideas.
The Visual Studio built-in database tools tend to use System.Data.OleDb for their database manipulations. What you are seeing is an unfortunate limitation of the Access OLEDB provider.
For an Access table named [fruits]
id fruit
-- -----
1 apple
2 banana
3 cherry
4 apricot
and an Access saved query named [qry_aFruits]
SELECT fruit
FROM fruits
WHERE fruit LIKE "a*";
the following C# code using System.Data.OleDb returns no rows
myConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\Users\Public\Database1.accdb;";
using (var conn = new OleDbConnection(myConnectionString))
{
conn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM [qry_aFruits]", conn))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Console.WriteLine(rdr["fruit"]);
}
}
}
}
However, the same code using System.Data.Odbc returns two rows, as expected:
myConnectionString =
#"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
#"Dbq=C:\Users\Public\Database1.accdb;";
using (var conn = new OdbcConnection(myConnectionString))
{
conn.Open();
using (var cmd = new OdbcCommand("SELECT * FROM [qry_aFruits]", conn))
{
using (OdbcDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Console.WriteLine(rdr["fruit"]);
}
}
}
}
So if you need to work with a lot of saved Access queries that use * as the LIKE wildcard then you'll probably have to forego the built-in Visual Studio database tools that are built on top of System.Data.OleDb (e.g., Data Sources and TableAdapters) and use ODBC.
No, there is no such setting. You will have to adopt one way or the other.

Error on Inserting to Ms Access Database (Unspecified Error \r\n Object invalid or no longer set)

I want to insert about 2000 records every time a button is clicked.
It works fine until record 511, and throw this exception:
Unspecified Error \r\n Object invalid or no longer set
I've debugged it several times with different records or different order and always get the same error on 511th record.
What's happening?
CODE:
(I read the ID of the last record, before i insert another one)
string CmdText = "SELECT TOP 1 Id FROM MyTable ORDER BY Id DESC";
OleDbCommand com = new OleDbCommand(CmdText,tran.Connection,tran);
com.CommandType = CommandType.Text;
OleDbDataReader reader = com.ExecuteReader(); //exception started here
It sounds like somehow the Jet engine is
not working properly or is corrupted.
When opening and closing connections or recordsets using the Microsoft ODBC Driver for Access or the Microsoft OLE DB Provider for Jet, the following error may be reported:
Object invalid or no longer set.
To resolve this problem, install the latest Microsoft Jet 4.0 service pack 6. For additional information FIX: "Object invalid or no longer set" Error with Microsoft Jet
I've figured it out guys.
I have to close OleDBDataReader every time i want to insert new record.
Now it works fine. Thanks.
The best way to resolve this problem is to delete that table in which its giving error in inserting / updating. and then re-create the table, but be sure, to backup the table data first.

Can't create a sql connection due to the fact that it won't rcognize the data source keyword

Hello I'm trying to run a simple sql command on a DB from MS VS C# 2010 and I have encountered a error I have never seen before the relevant code is:
SqlConnection comCon = new SqlConnection(#"Data Source=C:\\Users\\George\\Desktop\\programming\\C#workspace\\Projects\\Examen\\Examen\\Companie.mdf;Initial Catalog=Proiect;Integrated Security=True"); 
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE Proiect SET Buget = Buget + 500 WHERE (Buget > 0)";
cmd.Connection = comCon;                                                      
comCon.Open();
Console.WriteLine(cmd.ExecuteNonQuery().ToString());
comCon.Close();
And the error is Keyword not supported: 'data source'
The main problem is that I'm not used to creating these sqlconnections by hand so please tell me if I'm missing something.
You are using the wrong structure. To attach a database file, you need to use the following structure:
SqlConnection sqlConnection =
"Server=DatabaseServerName;AttachDbFilename=d:\Database\Database.mdf;
Database=DatabaseName; Trusted_Connection=Yes";
You need to have the right permissions on both the target file and database server to attach the databse and establish the connection.
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
If it's not an ASP.NET application don't use the DataDirectory syntax and just use the full c:... path.

error in stored procedure Access

I have created a query which is: SELECT Replace(column_name,a,b) AS expr1
FROM table1; the name of this query is:filepath.
I have wrote the following code in C#. when i compile the code it Syntax error in PROCEDURE clause.
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection= ren_connection1;
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "Execute filepath";
OleDbParameter oldfilevalue = new OleDbParameter();
oldfilevalue.ParameterName = "a";
oldfilevalue.OleDbType = OleDbType.VarChar;
oldfilevalue.Direction = ParameterDirection.Input;
oldfilevalue.Value = oldname2;
OleDbParameter newfilevalue = new OleDbParameter();
newfilevalue.ParameterName = "b";
newfilevalue.OleDbType = OleDbType.VarChar;
newfilevalue.Direction = ParameterDirection.Input;
newfilevalue.Value = oldname1;
cmd1.Parameters.Add(oldfilevalue);
cmd1.Parameters.Add(newfilevalue);
i = cmd1.ExecuteNonQuery();
//oldefile value can be like this: D:/myfile/pictures/cars/
//newfile value can be like this: D:/myfile/pictures/jeeps/
i want to replace in a row a string with another string without modifying the whole row..and i thought replace will work but it didnt :(
access version is:2007.
any idea or help will be greatly appreciated.
Thanks alot.
I am afraid Replace is only available if you are running within Access, as Vincent mentions, it is a VBA function, not a Jet/ACE function. Also discussed: Exception when trying to execute "REPLACE" against MS Access. I have replied to what i think is your first question, update table access, with a possible solution.
Try changing your commandtext with
cmd1.CommandText = "EXECUTE yourProcedureName";
Edit now that your procedure is invoked correctly you need to work around the missing "Replace" function (btw, have you tried Vincent Vancalbergh's suggestion to see if "Replace can be made to work? That would be much easier....)
What I was saying in the comments is that you could select the content of the table, perform the replace in c# code and (if needed) update your table with the new values.
your select becomes:
SELECT table1_id, column_name FROM table1;
and your code changes like this:
//you should change ExecuteNonQuery to ExecuteReader, since you want
// to read the results of your SELECT
OleDbDataReader rdr= cmd1.ExecuteReader();
//Iterate through the table
while(rdr.Read())
{
string currentValue=rdr["column_name"].ToString();
string newValue = currentValue.Replace(a, b);
//now do what you need with the row
// ...
}
I found the following here:
Prior to a company wide upgrade to XP
there was no problem with access
databases, so I am not sure if this
would be a solution to your issue. But
I had a problem similar to yours after
an upgrade to XP from 2000 with some
access databases. Undefined Function
"Replace" errors started to pop up. At
the end of the day it turned out to be
the version of VBA installed. 6.0
versus 6.3. The problem machines had
6.0 installed. Start access Help -> About MS Access -> SYSTEM INFO ->
APPLICATIONS -> Microsoft Access 2000
-> SUMMARY. The VBA version of 6.00 produced the error, VBA version 6.03
no problem. Take Care, Nick
Now the question is, what VBA version are you using?
The solution is in #onedaywhen's answer her:
Exception when trying to execute "REPLACE" against MS Access
It uses Mid(), Len() and InStr() in place of Replace().

Categories

Resources