My query file looks like this:
USE DB_A
GO
SELECT * FROM sch.table;
but my connection string, because of some reason, should be forced to set as #"Data Source=SERVER;Initial Catalog=DB_B; ......"
As ExecuteNonQuery() doesn't support GO, this query will be separated into two parts, i.e, actual code looks like this:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnString;
OleDbCommand cmd = new OleDbCommand();
conn.open();
cmd.ComandText = "USE DB_A";
cmd.ExecuteNonQuery();
cmd.ComandText = "SELECT * FROM sch.table";
cmd.ExecuteNonQuery();
conn.close();
it seemsUSE DATABASE doesn't work, it is still reporting errors cannot find object sch.table when executing.
is there any neat solution other than changing my query file or my connection string?
As you've noticed USE doesn't work here. What you can do is fully reference your objects. So instead of
SELECT * FROM sch.table
write
SELECT * FROM DB_A.sch.table
Note that this will only work if you can access DB_A from DB_B with the same credentials you've used to connect to DB_B. If this is not the case you'll have to use a seperate connection to DB_A.
A Solution available is just remove the initial catalog Initial Catalog=DB_B from connection string. Not a perfect solution to this question, but worked in my case.
Related
I am trying to create to a local database via a mdf file, like so:
scon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDBFilename=|DataDirectory|\articles.mdf; Integrated Security=True");
scon.Open();
scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)");
scmd.Parameters.AddWithValue("#url", "http://google.com");
scmd.ExecuteNonQuery();
MY mdf file is in the root folder, and in the debug folder too. When I run the following code I get an error saying the following:
I can't use the full connection path because it's a long url with spaces, here is my file structure:
My database exists:
How can I fix this so I can connect to my database?
Pass the connection object to the SqlCommand constructor
scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)", scon);
The connectionstring is fine, the error message informs you that it is not possible to execute a command if the database is not known. The SqlConnection contains this information and you need to pass it to your command.
Another possibility is through the
scmd.Connection = scon;
but, personally, I prefer to pass that info in the constructor.
Final but really important note:
SqlConnection and SqlCommand are disposable objects. You should always dispose these kind of objects. The using statement is the correct method
using(scon = new SqlConnection(....))
using(scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)",scon))
{
scon.Open();
scmd.Parameters.AddWithValue("#url", "http://google.com");
scmd.ExecuteNonQuery();
}
The Problem With Your Code Is That You Have A Command and a Connection But There Is Nothing To Till The Command To Use This Connection Object ... You Can Use The SqlCommand Constructor To Do That
scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)",scon)
Or Use The Connection Property Of The SqlCommand Class Like This
scmd.Connection = scon
Consider Adding Using To Your SQL Connection ... Or Else You Will Have To Manually Close The Connection By Calling scon.Close();
if You Didn't Do either Of Those You Will Run Into An Exception If Your Tried To Open The Connection Again While It's Already Open
I have got an UPDATE query, what works well when I execute it in MS Managment Studio.
But if I try execute this query from my c# app, it executes without any exceptions, but does not update the table. Connection string is right.
This is the way I do it:
int contractId = 2
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\tst.mdf;Integrated Security=True;Connect Timeout=30";
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "update аренды set datetime_возврата=GETDATE() where id_договора=#contractId";
cmd.Parameters.Add("#contract_id", SqlDbType.Int, 4).Value = contractId;
cmd.ExecuteNonQuery();
What can be wrong?
If your c# code executes without any exceptions, it updates the database too, but please note you are used AttachDbFilename=|DataDirectory|\tst.mdf in your ConnectionString means the database that is updated is located in the sub-folder BIN\DEBUG folder of your project. If you want to see the updated data just attach the database located in the bin/debug folder in SSMS.
Also as Steve mentioned in comments, for more details read this post.
I am trying to specify the default schema/instance as part of a connection string (or specific command) so it does not need to be part of the query.
OdbcConnection conn = new OdbcConnection("Driver={IBM DB2 ODBC DRIVER}; Database=myDB; Hostname=myHostName; Port=myPort; Protocol=TCPIP; Uid=myID; Pwd=myPW;");
OdbcCommand comm = new OdbcCommand("select count(*) from customers", conn);
conn.Open();
var value = comm.ExecuteScalar();
conn.Close();
Unfortunately this fails with the error:
ERROR [42S02] [IBM][CLI Driver][DB2] SQL0204N myID.customers is an undefined name. SQLSTATE=42704.
Notice it's using myID where the Schema/Instance should be. If I specify the schema/instance explicity:
OdbcCommand comm = new OdbcCommand("select count(*) from mySCHEMA.customers", conn);
it works as expected. I'd like to specify mySCHEMA as part of the Connection String, similar to "Initial Catalog" when using MS SQL Server.
After a bunch of experimentation and googling, I can't seem to figure it out. Any ideas?
Wow, this one was obvious. I just need CurrentSchema=mySCHEMA in the connection string.
For some reason I didn't connect that dot right away after working through http://www.connectionstrings.com/ibm-db2 (tried all sorts of variations like Schema, Default Schema, etc). Hopefully this helps someone in the future...
I am developing an ASP.Net website. I have to execute a query which fetches data from two different database.
I have two SqlConnection objects for these connections.
I have both the connections open. But in SqlCommand object, I can specify just one SqlConnection object.
SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=xxx1;User ID=web_writeonly;Password=aaa;Network Library=DBMSSOCN");
SqlConnection conn1 = new SqlConnection("Data Source=xxx;Initial Catalog=xxx2;User ID=randomUser;Password=bbb;Network Library=DBMSSOCN");
conn.open();
conn1.open();
SqlCommand cmdUserInfo = new SqlCommand("<query goes here>", conn);
cmdUserInfo.Parameters.Add("#ifa", SqlDbType.NVarChar).Value = ifacode;
SqlDataAdapter sdaUserInfo = new SqlDataAdapter(cmdUserInfo);
sdaUserInfo.Fill(dtSummaryTbl);
conn.Close();
conn1.Close();
When I execute this code snippet, I get an error "The SELECT permission was denied on the object '*', database 'xxx2', schema 'dbo'."
Please help me out in sorting this problem.
Thanks!
That error means that you don't have sufficient permissions... check what sql login your website is associated with and then the permissions on the table you're trying to select data from.
Also, on closer inspection, one of your usernames is "web_writeonly"... kind of a hint if you're trying to do a select!!! ;)
Assuming your databases are on the same server why can't you just put your SQL into a stored procedure on one of the databases. I am pretty sure you can then just use one connection object and execute your stored procedure which gets data from two databases.
when i run a query like this:
SqlDataAdapter dap = new SqlDataAdapter("select * from some table", myConnection);
before doing the select, should i be doing "use somedatabase; go" ??
No, your database and schema should be set in the connection string for myConnection.
No you should specify the database name in myConnection
InitialCatalog = [databaseName]
Your connection string should something look like this
data source=[ServerName];Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=[DatabaseName];
I imagine myConnection is already specifying a default catalog (i.e. database) in its connection string, so you don't need to use the use line.
See here for details.
No; the myConnection object's connection string should define which database needs to be used, along with the server and login information.
That should all be in the myConnection variable, since I presume that contains the connection string.
Although you might want to call using on the DataAdapter
using(SqlDataAdapter dap = new SqlDataAdapter("select * from some table", myConnection)
{
//do stuff with dap here
}//dispose of dap
Since it does inherit from something that implements IDisposable.
Your connection string tells it what database to connect to.
connectionString = "Data Source=SERVERNAME; Initial Catalog=DATABASENAME; Integrated Security=SSPI;";
That would create a connection to a server and database using windows authentication.