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().
Related
I've got a parameters table where I've got a parameter to say whether my program should run, I'm trying to get this value to check for a function.
Here is the function
private static bool shouldRun()
{
OracleCommand c = conn.CreateCommand();
c.CommandText = "select value from parameters where lower(name) = lower('valuetocheck')"; // this one doesn't work
//c.CommandText = "select 'Y' from dual"; - This one works
c.CommandType = System.Data.CommandType.Text;
OracleDataReader dr = c.ExecuteReader();
dr.Read();
string s = dr.GetString(0); // exception on this line
return false;
}
The additional information is below:
Invalid operation on a closed object
I've tried selecting from dual, as you can see above, which works perfectly fine, but when I try to run the actual query it doesn't like it. I've checked the query in SQL Developer and it works fine.
I've had a look around SO and other websites and the only information I could get on this issue was that the command wasn't associated with a connection, which as you can see above it is.
I've also tried just doing
OracleCommand c;
c.Connection = conn;
Which also doesn't work.
Any insight into this would be great, thanks!
I had the same issue recently. I got the "Invalid Operation on a closed object" but when I debug the code, it was the OracleDataReader that was closed and not the OracleConnection. My problem was the query retuned an empty response and the DataReader closes itself if there is no data. So my resolution was simply checking if the data reader have any rows by adding the following..
dro.Read();
if (dro.HasRows)
{
//Do your
}
I hope it helps someone.
When Oracle gives this error - "Invalid Operation on a closed object", more often than not, what actually happens is that the user does not have access privileges to the objects they are trying to access in the database. Check your connection string and make absolutely sure that the user listed in that connection string does have privileges to the objects in your query - in this case, read access to the Parameters table.
NOTE: While the information in this answer does not directly fix the issue in the original question, I found this question and the other answers very helpful in pinpointing the solution to another related scenario.
When changing from the unmanaged Oracle.DataAccess library to the managed Oracle.ManagedDataAccess library, we found a very tricky difference. Apparently, with the unmanaged library, the dr.Read() call is not required for the fetch to happen, but it most definitely is required with the managed library.
After switching to the managed library, all of our calls constructed similar to the example in the question needed to have dr.Read() added before trying to get any data out of the dr object, otherwise we would get the same "Invalid operation on a closed object" message.
Check your connection String
Replace conn.State == ConnectionState.Closed with conn.State != ConnectionState.open
For me the issue was in this part of my code -
(dt is the object of DataTable in the below code samples)
using (var reader = lSqlCommand.ExecuteReader())
{
while (reader.Read())
{
dt.Load(reader);
}
}
When I removed the while part it got resolved. The working part now is like -
using (var reader = lSqlCommand.ExecuteReader())
{
dt.Load(reader);
}
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.
Before I start, I'll let you know that I tried everything that has already been suggested on previous questions and other websites before I considered posting a question myself. As it happens, nothing seems to work and I'm just about fed up with this.
As some background information, this is for my Computing A2 project, so I'm kind of stuck for time now - i.e. I can't be changing loads of my code ideally.
Anyway, onto the issue...
I'm using SQLCe in my code to read from various tables and write to one. So far, the code for reading from the tables works fine, so that's any connection issues out the way first. The piece of code I am struggling with is as follows:
string connectionString = Properties.Settings.Default.BookingSystemDatabaseConnectionString;
using (SqlCeConnection myConnection = new SqlCeConnection(connectionString))
{
myConnection.Open();
try
{
string commandStr = "INSERT INTO bookings(username, room, time) VALUES(#username, #room, #time)";
SqlCeCommand myCommand = new SqlCeCommand(commandStr);
//Passes parameters into SQL command.
myCommand.Parameters.AddWithValue("username", StaticUser.StudentUser.username);
myCommand.Parameters.AddWithValue("room", roomBox.Text);
myCommand.Parameters.AddWithValue("time", timeBox.Text);
//Executes SQL command. Returns the number of affected rows (unecessary for my purposes; a bi-product if you will).
myCommand.ExecuteNonQuery();
}
catch
{
System.Windows.Forms.MessageBox.Show("Could not write new booking to database. This is likely because the database cannot be reached.", "Error");
Program.AccessError = true;
}
myConnection.Close();
}
This is just one of the many ways I have tried to combat the issue I am having. I have also explored:
myCommand.Parameters.Add(new SqlCeParameter("username", StaticUser.StudentUser.username));
to pass the parameters...and another method which escapes me now (using ".Value = StaticUser.StudentUser.username" I think). Furthermore, I have tried using a 'using' statement for the command to save me closing the connection myself (I will probably end up using a solution that uses 'using'). Finally (albeit this isn't a chronological recollection), I tried:
SqlCeCommand myCommand = new SqlCeCommand("INSERT INTO bookings(username, room, time) VALUES(#username, #room, #time)", myConnection)
Again, of course, to no avail.
To highlight the actual symptoms of the issue I am having: The code appears to run fine; stepping through the full method I have pasted above shows that no error is being caught (of course, the message box does not appear - I realised afterwards that stepping through was arguably an unnecessary procedure) and in the other methods I have touched on, the same thing happens. The issue, then, is that the table 'bookings' is not actually being updated.
So, my question, why?
I didn't do the obvious and check the Debug folder for an updated database.
Look for a copy of the database file in your bin/debug folder.
Use full path in connection string, and preferably do not include the sdf file in your project (or at least set build action to None)
i think you are not defining a connection for the command
try
mycommand.connection = connectiostring;
I have at small web-application that get some data from a SQLdb in Visual Studio 2010. When i try to display this, using a simple dropdownlist it takes around 15 sec the first time just after compilation and then after that 5 sec every request. I use a LINQ connection to db and a repeater to print everything out. It´s four columns and around 50 rows, so not so mutch data. It doesn´t matter if i try take 10 rows, same response time.
We have tested the same thing on another computer with VS2008 installed and the time was like 0.1 sec or something like that. I use .NET 3.5 and have installed all the latest updates (SP1 and so).
If i look at the trace i see it takes time at these rows in my code:
var cust = dbContext.Customers
.Select(c => new
{
c.customerID,
c.Email
}).Take(10);
repeater.DataSource = cust;
repeater.DataBind();
Anybody know what could be taking som mutch time?
Regards
Daniel
I have tried this other aproach:
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text; //default
cmd.CommandText = "SELECT Email FROM Customer";
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
It takes just as long.. there must be some other more fundamental problem than the code to call the db i think?
Some more information:
I did som trace, this is first time page is loaded:
Begin Raise ChangedEvents 0,00219604937555932 0,000014
After repeater has printed 15,8138335259613 15,811637
End Raise ChangedEvents 15,8138801733289 0,000047
Second time:
Begin Raise ChangedEvents 0,00219604937555932 0,000014
After repeater has printed 5,25090396258066 5,248825
End Raise ChangedEvents 25095106283536 0,000047
What´s happening at ChangeEvents?
Get the actual SQL being generated by LINQ, copy-paste it to your database management tool and look at the execution plan to identify potential performance issues.
You can see the actual SQL by using Log property of the data context. In a console application, you can do this:
dbContext.Log = Console.Out;
// ...
Or, write the SQL to file like this:
using (var writer = new StreamWriter("sql.log")) {
dbContext.Log = writer;
// ....
}
Also, it might be worth adding ToList() or ToArray() at the end of your LINQ expression, just to make sure it is not unintentionally re-executed.
I have no idee what i did to make it work.. just kept on doing stuff at other places in the code and updated latest windows update.. hmm.. now it work like a charm, must be a bug in VS2010??
Thanks for all suggestions though, learned some great stuff!
Regards
I'm new to databases and am trying to add a new record using SQL. The code runs fine the first time, but the second time throws an error saying that it can't write duplicates to a unique key. The third time runs fine, but the fourth time throws the error. Basically, it seems that every other time, the error is thrown. I understand why the error would be thrown if data was written, but when I examine the database, it remains empty. What am I doing wrong in my code that is causing the query to not bother writing the data?
EDIT If I enter the SQL directly within the database, it works. It doesn't work when I use the C# code below.
using (SqlCeConnection con = new SqlCeConnection(conString))
{
con.Open();
using (SqlCeCommand com = new SqlCeCommand("INSERT INTO User (Name, Age, URL) VALUES ( #name, #age, #url )", con))
{
com.Parameters.AddWithValue("#name", "James Y");
com.Parameters.AddWithValue("#age", 28);
com.Parameters.AddWithValue("#url", "www.example.com" );
com.ExecuteNonQuery();
}
}
I've partially figured it out. Apparently you have to also download SQL CE Tools for Visual Studio. I did this and I had a new option to include SQL CE 4 into my project (I was using the SQLCE option, assuming that it would use 4.0 by default since that's the one I installed). Only problem now is that when I try and add it, it says that it's not supported by the project type (Console project). I saw a post on MSDN that said that SQLCE 4 was for web-only projects but it was a post from a few months back and the current download page says it's for web or desktop applications. Either way, this is proving to be too much of a hassle to bother with and so I'm just going to look for an alternate database if I can't resolve this soon.
FIXED I uninstalled SQLCE4 and the SQLCE Tools, then reinstalled them.
Try and do the following as your SQL:
INSERT INTO [User] (Name, Age, URL) VALUES ( #name, #age, #url )
User is a reserved word in sql server. You should try not to name your table as "user".
Name is a reserved word. Wrap it in []
using (SqlCeCommand com = new SqlCeCommand("INSERT INTO User ([Name], Age, URL) VALUES ( #name, #age, #url )", con))
Since you use DataDirectory in your connection string, the file is copied to your bin/debug folder, so you have several copies of the database, one in your project and one in your debug folder. Make the connection string a full path to avoid any confusion while debugging!