Cannot find the object because it does not exist - sql-server-2008

I did spend an hour searching before I posted about this problem.
The table does exist and I can query that table and I can see the resultset but when i try to execute from Visual Studio 2008 I get the below error:
Cannot find the object "Products" because it does not exist or you do not have permissions
Why does this error occur and what should I do to resolve it?
using (System.Data.SqlClient.SqlCommand cmd = connection.CreateCommand() as System.Data.SqlClient.SqlCommand)
{
cmd.CommandText = "SET IDENTITY_INSERT Products ON";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
I tried specifying dbo.Products and before executing I also tried use dbname but that did not help.

after spent few hours and lost few hairs i found that the problem was in the connection strings (but this is still did not convence me) and as i said in question i was not having any issues but suddenly its pop-up and i havent change anything (who knows what dba have changed)
so I try tweak my connection string instead, and it does make a string
to see if it makes a difference: and it does.
c.Provider = 'sqloledb'
dsn = 'Server=MyServer;Database=MyDB;Trusted_Connection= Yes'
c.Open(dsn)
the only thing i have added to my connection string is Trusted_Connection= Yes
PS: SET IDENTITY_INSERT remains on for your session until
you turn it off, and it can only be on for one table at a time
Hope this will help others...

The error is happening because you haven't set a database context yet. If you added "use (dbname) go " (with your database name) to the start of the query it would work.
[edit]
Sorry didn't spot that you'd tried that. Maybe your connecting to the wrong server? Try changing the query in code to "create table argh (argh int)" and check it fails the second time. Then track down where it created it!

Related

How to Close a Connection When Using Jupyter SQL Magic?

I'm using SQL Magic to connect to a db2 instance. However, I can't seem to find the syntax anywhere on how to close the connection when I'm done querying the database.
you cannot explicitly close a connection using Jupyter SQL Magic. In fact, that is one of the shortcoming of using Jupyter SQL Magic to connect to DB2. You need to close your session to close the Db2 connection. Hope this helps.
This probably isn't very useful, and to the extent it is it's probably not guaranteed to work in the future. But if you need a really hackish way to close the connection, I was able to do it this way (for a postgres db, I assume it's similar for db2):
In[87]: connections = %sql -l
Out[87]: {'postgresql://ngd#node1:5432/graph': <sql.connection.Connection at 0x7effdbcf6b38>}
In[88]: conn = connections['postgresql://ngd#node1:5432/graph']
In[89]: conn.session.close()
In[90]: %sql SELECT 1
...
StatementError: (sqlalchemy.exc.ResourceClosedError) This Connection is closed
[SQL: SELECT 1]
[parameters: [{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__s ... (123202 characters truncated) ... stgresql://ngd#node1:5432/graph']", '_i28': "conn = connections['postgresql://ngd#node1:5432/graph']\nconn.session.close()", '_i29': '%sql SELECT 1'}]]
A big problem is--if you want to reconnect, that doesn't seem to work. Even after running %reload_ext sql, and trying to connect again, it still thinks the connection is closed when you try to use it. So unless someone knows how to fix that behavior, this is only useful for disconnecting if you don't want to re-connect again (to the same db with the same params) before restarting the kernel.
You can also restart the kernel.
This is the most simple way I've found to close all connections at the end of the session. You must restart the kernel to be able to re-establish the connection.
connections = %sql -l
[c.session.close() for c in connections.values()]
sorry for being to late but I've just started with working with SQL Magic and got annoyed with the constant errors appearing. It's a bit of a awkward patch but this helped me use it.
def multiline_qry(qry):
try:
%sql {qry}
except Exception as ex:
if str(type(ex).__name__) != 'ResourceClosedError':
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
print (message)
qry = '''DROP TABLE IF EXISTS EMPLOYEE;
CREATE TABLE EMPLOYEE(firstname varchar(50),lastname varchar(50));
INSERT INTO EMPLOYEE VALUES('Tom','Mitchell'),('Jack','Ryan');
'''
multiline_qry(qry)
log out the notebook first if you want to close the connection.

Query unexpectedly fails

I am creating a simple member system using MySQL, and have stumbled onto a problem.
The issue is that I am using the correct SQL query to search the column Username, and find Administrator, but however my query isn't finding anything.
I have searched the internet for a solution (with many results taking my back to Stack Overflow), but however have not found anything.
The query that I am using is:
SELECT * FROM members WHERE Username = "Administrator"
Which looks find from my end, but however does not return any results:
Am I doing something wrong here?
I am new to MySQL & PHP, so if something is obviously wrong with what I'm doing here, please tell me nicely, and please don't 'flame'.
Edit:
When attempting to run this query though PHP, I get:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/crysisor/public_html/checklogin.php on line 22
The above code confirms that something is wrong...
Relevant code:
$user = mysqli_real_escape_string($sqli, $_POST['user']);
$pass = mysqli_real_escape_string($sqli, $_POST['pass']);
if ($user && $pass) {
$checkuser= mysqli_num_rows(mysqli_query($sqli, "SELECT * FROM users WHERE Username='".$user."'"));
I have a few hints which may help you resolve your problem.
Make the query itself a PHP variable, and echo it. Then copy and paste the echoed result into phpMyAdmin.
Use single quotes for query variables. The query itself should be in double quotes.
Unrelated: the password looks short. It shouldn't be stored in plain text.

EntityFramework on MySql changing connection string does not change results data

I'm working with EntityFramework 5.0 and MySql. I have generated model from database, and my application now have to connect on multiple database with same structred data.
So i have to dynamic change connection string based on some info.
I try to change database name even from config section of connection string, and with EntityConnectionStringBuilder, but i had the same result: my new connection is stored correctly, but data returned are of the first database.
From WebConfig:
add name="dbIncassiEntities" connectionString="metadata=res:///DAL.Modelincassi.csdl|res:///DAL.Modelincassi.ssdl|res://*/DAL.Modelincassi.msl;provider=Devart.Data.MySql;provider connection string="user id=root ... database=dbname2"" providerName="System.Data.EntityClient" />
From code:
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
entityBuilder.ProviderConnectionString = "user id=...database=dbname2";
entityBuilder.Metadata = #"res://*/DAL.Modelincassi.csdl|res://*/DAL.Modelincassi.ssdl|res://*/DAL.Modelincassi.msl";
var context = new dbIncassiEntities(entityBuilder.ToString());
My constructor:
public dbIncassiEntities(string conn)
: base(conn)
{
}
What am i missing?
UPDATE
I can see that calling a query directly from SqlQuery, results returned are correct,
while using the generated entities i retrieve wrong data.
var test = context.Database.SqlQuery<string>(
"SELECT cognomenome FROM addetto limit 0,1").ToList();
But calling..
var oAddetto = from c in context.addettoes select c;
So my problem is only on the model itsself, and manually changing the generated schema
<EntitySet Name="addetto" EntityType="dbIncassiModel.Store.addetto" store:Type="Tables" Schema="dbname2" />
..i'll get the right information.
My question now is: how can i change in code these informations??
Any help is really appreciated!!
Thanks, David
Ok, i've found a workaround for now.
I simply clear the shema name on the designer, and now i can call the generated entities succesfully. Hope this can help anyone else.
David
While I could not remove the Schema in the designer, I removed it directly in the .edmx file. Do a full text search for Schema="YourSchema" in an XML editor of your choice and remove the entries. After that, changing the connection string is enough.
Downside is, the Visual Studio designer and mapping explorer won't work properly anymore.
This seems to be more of a dotConnect issue rather than MySQL, since the problem also exists for the Oracle adapter:
http://forums.devart.com/viewtopic.php?t=17427

controlling ArithAbort in EF4

We are having some performance issues with our EF4 MVC solution. We've been able to track it down to ArithAbort getting set to off before all connections to the database, and now we are trying to force it to stay as 'ON'.
We've looked at:
How do you control the "SET" statements emitted by Linq to SQL
But it seems like EF4 is resetting the connection before each query, so that won't work.
So far we've tried "set ArithAbort on" before a given query, with no luck. We've also tried going the long way and making a new connection where we set it, but still no luck.
So, anyone have a clue as to how we can get it to set it before making any linq queries against the database?
Changing database settings isn't an option.
Edit:
Per Andiihs suggestion I tried out the wrapper solution and added in the following lines of code to the EFCachingCommand class
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{
if (this.WrappedCommand.CommandType == System.Data.CommandType.Text)
{
this.WrappedCommand.CommandText = "set arithabort on; " + this.WrappedCommand.CommandText;
}
This essentially ensures that any Linq-sql calls get prefixed with the right set statement.
I also had to add:
DbFunctionCommandTree functionTree = commandTree as DbFunctionCommandTree;
if (functionTree != null)
{
this.IsModification = true;
return;
}
To the GetAffectedEntitySets function in the EFCachingCommandDefinition, in order to get it to work properly with stored procedure calls.
EF provides the ability to insert a Wrapping Provider between Entity Connection and SQL.Data.Client - see http://code.msdn.microsoft.com/EFProviderWrappers and http://blogs.msdn.com/b/jkowalski/archive/2009/06/11/tracing-and-caching-in-entity-framework-available-on-msdn-code-gallery.aspx
Now I admit this is more of a clue than an answer - but perhaps you can insert the relevant set at this point ?

Could not find server 'dbo' in sys.servers

I have a lot of services which query the database. All of them work fine but one service calling a stored procedure gives me following error:
Could not find server 'dbo' in
sys.servers. Verify that the correct
server name was specified. If
necessary, execute the stored
procedure sp_addlinkedserver to add
the server to sys.servers.
I have not idea why all the other stored procedures work fine and this one not...
By the way, I use SubSonic as data access layer.
Please run select name from sys.servers from the server which you mentioned as default server in configuration file.
Here in name column values should match with your server names used in the report query.
e.g serverXXX.databasename.schema.tablename
serverXXX should be there in the result of select name from sys.servers otherwise it gives error as got.
It sounds like there is an extra "." (or two) in the mapping - i.e. it is trying to find server.database.schema.object. Check your mapping for stray dots / dubious entries.
Also make sure that the server name matches what you think it is. If you rename the host that SQL Server is running on, you need to rename the SQL Server, too.
http://www.techrepublic.com/blog/datacenter/changing-the-name-of-your-sql-server/192
I had another issue with the same exception so I'll post here if someone stumble upon it:
Be careful if you specify the server name in synonyms. I had a different server name on my staging machine and production and it caused the same 'cannot find server'-error.
(Guess you shouldn't use synonyms that much anyway but it's useful in some migration scenarios)
In my case i was facing same issue with following ,
SqlCommand command = new SqlCommand("uspx_GetTemplate", connection);
but after adding square bracket to stored procedure name it get solved.
SqlCommand command = new SqlCommand("[uspx_GetTemplate]", connection);