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.
Related
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();
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 am trying to create an application which will synchronize its database with another software's database..
Problems are:
How will the database will synchronize with external database after I have created the installer and installed..i.e. how will it take the connection string.
I am looking for a solution which will provide a button to select the required database and based on the selection automatically generate the connection string.
Is it possible to run SQL create queries on external database while installation after the database is selected via browse button?
You have an option to create a Connection Settings form, which will help user to construct the connection string.
Yes, it's possible. It looks something like this:
using (var sqlConnection = new SqlConnection(#"Data Source=myServerAddress;User Id=myUsername;Password=myPassword;"))
{
sqlConnection.Open();
string query = "CREATE DATABASE...";
using (var sqlCommand = new SqlCommand())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = query;
sqlCommand.ExecuteNonQuery();
}
}
If it won't work, try to set Initial Catalog to master:
#"Data Source=myServerAddress;Initial Catalog=master;User Id=myUsername;Password=myPassword;"
While I establish a connection to SQL Server using ADO.NET, it showing errors.
Following is the code:
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=abdul;Integrated Security=true");
SqlCommand cmd = new SqlCommand();
con.Open();
String str="select * from emp where empname='Abdul'";
cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr == null || !dr.HasRows)
{
MessageBox.Show("No Records found");
}
else
{
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
}
When I am running the project it showing the following error:
Cannot open database "abdul" requested by the login. The login failed.
What have to do?
The login is successful at the the SQL Server level. Then either
the database exists but the login you are using doesn't have access to the database
the database doesn't exist
In SSMS, go to adbul database. Expand the security node and add the relevant users (which map to the login) + security there. If you still can't, have you created the database single user?
It's hard to give more details at the moment.
You need to check that the user you are connecting with is a valid SQL Login, and that the password supplied is correct. You also need to ensure the login has an associated SQL User in the database they are trying to connect to.
SQL Logins are used to access the server itself, and they are mapped to database SQL users.
You said you created the database. How did you do this? Was it from sql management studio? If so, was this in the same Windows session as you are executing the program code above?
I ask because if you could create a database, I believe you should be able to connect to it.
I'd look at the difference between successfully connecting with Sql Management Studio and trying to get past the 3rd line of code in your question. (assuming that's where it fails, maybe even edit the question to take out the lines beyond).
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.