Connecting to local database - c#

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

Related

Compare tables between two MDF files

I am attempting to synchronizing tables in two different .MDF files. After successfully creating a datatable for the first file I get an error when trying to create the second:
Cannot attach file 'E:\JVT-Inventory.mdf' as database 'JVT-Inventory' because this database name is already attached with file 'C:\Database\JVT-Inventory.mdf'
I have created separate procedures for each connection to create the tables then disposed the connection. Both the datatable and adapter are global variables to be used in my routines to compare the tables. None of the online research seems to apply to what I am trying to accomplish.
string conString;
conString = "Data Source=(LocalDB)\\v11.0;attachdbfilename=" + #txtPath.Text + ";Initial Catalog=JVT-Inventory;integrated security=True";
using (SqlConnection connection = new SqlConnection(conString))
{
daRemote = new SqlDataAdapter("SELECT * FROM tblProduct ORDER BY keyPartNo", connection);
SqlCommandBuilder cbRemote = new SqlCommandBuilder(daRemote);
daRemote.Fill(dtRemote);
connection.Dispose();
This connection is made to a file on a flash drive.
The issue appears to be that the MDF file remains open until I exit the application. My question now is, how do I close the MDF file from within my application?
After searching many articles about working with databases I figured out the follow:
SqlConnection cnRemoteBye = new SqlConnection();
SqlCommand cmdRemoteBye = new SqlCommand();
cnRemoteBye.ConnectionString = #"Data Source=(LocalDB)\v11.0;Integrated Security=True";
cmdRemoteBye.CommandText = "ALTER DATABASE [JVT-Inventory] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [JVT-Inventory]";
cmdRemoteBye.Connection = cnRemoteBye;
cnRemoteBye.Open();
cmdRemoteBye.ExecuteNonQuery();
cnRemoteBye.Close();

execute SQL script with USE DATABASE in C#

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.

Making a copy of an azure database

I need to make a copy of an azure database but I don't have access to any management tools, only a connection string.
I know that to use the CREATE DATABASE x AS COPY OF y command I need to be in the master database but I don't know how to tell Azure to run my command from there. For example, I have this code:
var commandText = "CREATE DATABASE foobar AS COPY OF " + database;
var connectionString = <my_connection_string>;
using (var conn = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(commandText, conn))
{
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
}
}
which fails with error "User must be in the master database" - as I expected.
However my connection string is not valid for the master database, so how do I execute this command from the master database? If I was in SQL Management Studio I would just do:
use master
CREATE DATABASE x AS COPY OF y
Is there any way of emulating that in my code?
Change your connection string to access the master database instead of your regular one. It's as simple as that and the only solution.

How to execute a query which uses multiple database

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.

running a query from C# on sql server

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.

Categories

Resources