I have set up a database (QCDB) in my SQLEXPRESS instance. I have added a user (QCast) with serveradmin, sysadmin, and public server roles enabled at the server level. The user has db_owner role at the db level. But when connecting to the db with the below command in VS
string strConn = "Data Source=STA15-DT-ADM\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Microsoft SQL Server\\MSSQL14.SQLEXPRESS\\MSSQL\\DATA\\QCDB.mdf;User Id=QCast;Password=QC#st; Connect Timeout=30";
SqlConnection con = new SqlConnection(strConn);
string dbget = "SELECT WOnum WOstatus FROM WOdetail";
SqlCommand cmd = new SqlCommand(dbget, con);
con.Open();
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Results");
ad.Fill(dt);
WOgrid.ItemsSource = dt.DefaultView;
cmd.Dispose();
con.Close();
I get the following error
System.Data.SqlClient.SqlException: 'Unable to open the physical file "C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\QCDB.mdf". Operating system error 5: "5(Access is denied.)".An attempt to attach an auto-named database for file C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\QCDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.'
Not sure what I am doing wrong.
I got this one after more Google
I simplified the connection string and it took right off. not sure why.
string strConn = ("Data source = [Server Name]; Initial catalog = [db name]; User id = XXXX; password = XXXX");
Related
I have SQL Server 2016 LocalDB (.mdf file) and I want make backup of my database. I use the code shown below, but it does not work. I tested all code that exists in stackoverflow, but none of them worked.
Here is my code (this code works perfectly on SQL Server 2014 but does not work on localdb):
SqlConnection connect;
string con = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database\ClassSRM.mdf;Integrated Security=True";
connect = new SqlConnection(con);
connect.Open();
SqlCommand command = new SqlCommand(#"backup database " + Application.StartupPath + #"\Database\ClassSRM.mdf" + " to disk ='" + strFileName + "'", connect);
command.ExecuteNonQuery();
connect.Close();
I have win application and i get this error when i want to connect the database to my app
error:
An attempt to attach an auto-named database for file C:\Users\Aren\Desktop\DB\REGISTRATION.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
public class DALBase
{
protected SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\\Users\\Aren\\Desktop\\DB\\REGISTRATION.mdf;integrated Security=true ; User Instance=True");
protected SqlCommand com = new SqlCommand();
protected SqlDataAdapter da = new SqlDataAdapter();
protected DataSet ds = new DataSet();
}
public DataSet GetStudent(string filter)
{
DataSet dset = new DataSet();
using (SqlCommand cmd = new SqlCommand())
{
string cmdstring = string.Format("Select * from {0}"
, Common.Data.Student.Table_Name);
if (!string.IsNullOrEmpty(filter)) cmdstring += " where " + filter;
cmd.CommandText = cmdstring;
cmd.Connection = this.con;
cmd.Connection.Open();
cmd.CommandText = cmdstring;
cmd.Connection = this.con;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dset, Common.Data.Student.Table_Name);
return dset;
}
}
NOTE: ALSO i got 3 project in my solution the DALBASE and GETSTUDENT methods are in one project and i call them from other project to get the data for me.
I believe i have encountered this problem in the past. in my situation I loaded an application in visual Studio which when run would load a database and attach to SQL Server. Somehow when I closed the application it didn't deattach the database from SQL SERVER and next time I ran the app it complained with a similar if not the same message.
If you have SSMS installed open up to the .\SQLEXPRESS instance and see if you have a Registration*.mdf file attached. Or if you don't have SSMS open up your command line and type...
sqlcmd -S .\SQLEXPRESS -Q "select name from sys.databases"
This will show you all your databases attached/online on that instance.
Hope this helps.
I am a developer building websites in VB.Net using Visual Studio 2010. I am trying to populate some fields when a user visits a website based on their decisions on a previous screen.
My connection information is as follows:
Dim myDataReader As SqlDataReader
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim strSQL As String
myConnection = New SqlConnection("Data Source=localhost\sqlexpress; Database=PREP; Integrated Security=SSPI;")
Try
myConnection.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
strSQL = "SELECT * FROM Charts where ID=1"
myCommand = New SqlCommand(strSQL, myConnection)
myDataReader = myCommand.ExecuteReader()
If myDataReader.Read() Then
TextBox1.Text = myDataReader.Item("Priority1")
Else
MsgBox("Didn't work...")
End If
The error I continue to get is:
Cannot open database "PREP" by the login. The login failed. Login failed for user 'OR-AA-Me\Me'
I assumed that since it was a local database I would not need a username and password. Am I wrong?
Also, are there glaring practices in the above code that will be unwise when I transport this to a commercial environment?
Thanks!
Solved:
The connection string simply needed additional filepath information.
The successful connection information was:
myConnection = New SqlConnection("Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\PREP.mdf; Integrated Security=True; User Instance=True")
There was no need for a username as the Integrated Security set to True assumes that the computer will use the login information for the user on the actual computer he is using.
I have a search button to search the database by a name entered in a text box, this is working fine within visual studio but when trying to use this in the hosted version i get the following message:
Server Error in '/' Application.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
the code for this button is:
GridView2.Visible = True
lblEnterName.Text = ""
If txtLoanName.Text = "" Then
lblEnterName.Text = "Please enter a Bandie's Name"
Else
Dim conn As SqlConnection = Nothing
Try
Dim connString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BandDatabase.mdf;Integrated Security=True;User Instance=True"
conn = New SqlConnection(connString)
Dim query As String = "SELECT [SongName], [PartLearnt], [Status] FROM [Learning] WHERE ([BandieName] LIKE '%' + #Name + '%') ORDER BY [SongName]"
Dim cmd As SqlCommand = New SqlCommand(query, conn)
cmd.Parameters.AddWithValue("#Name", txtLoanName.Text)
conn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim dt As DataTable = New DataTable()
dt.Load(dr)
GridView2.DataSource = dt
GridView2.DataBind()
lblSearchBandieName.Text = "Progress for " + txtLoanName.Text
Finally
conn.Close()
End Try
End If
I am unsure why this is bringing the error as didnt before, all i have done is changed the page the button is on.
Thanks
did you check the information in the connection string? probably not an sqlexpres on the hosted solution. Also you may want to have the connection info in the web.config
Now as an answer....: -)
How to use the existing OLEDB connection Manager from scripttask Task(VB). i need to execute a SQL statement from "Script Task" Task.
Edit
Attempted the following code but couldn't get the connection with my OLEDB Connectionmanager
Dim MyCM As ConnectionManager = Dts.Connections("MyConnection1")
Dim CS As String = Dts.Connections(MyCM).ConnectionString
sqlConn = New SqlConnection(CS)
I would refer you to this most excellent blog post by Todd McDermid, Using Connections Properly in an SSIS Script Task
First you must add the connection manager to the script box:
Then, you access it in the code through the Connections object, e.g:
this.Connections.EBIC;
Check the link in the answer from user bilinkc for more detailed information
I don't remember the link where I found this. but it woks! (only you have to change to C# or find the way to put in VB it coud be easy)
SSIS has problems with cast Object_COM to IDTSConnectionManager, I wasted a lot of time with it, so OleDbConnection fix it.
Using your Connection Manager and the name of the connection OLEDB_NameConnectionTo_SQLServer,
if you use storesProcedures or function in the query the character "?" is important to put the parameters after, I really don't know why so off the hook
you have to add this refences.
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Data.OleDb;
...
try{
ConnectionManager cm = Dts.Connections["OLEDB_NameConnectionTo_SQLServer"];
IDTSConnectionManagerDatabaseParameters100 cmParams = cm.InnerObject as IDTSConnectionManagerDatabaseParameters100;
OleDbConnection conn = cmParams.GetConnectionForSchema() as OleDbConnection;
OleDbCommand cmd = new OleDbCommand("EXEC SP ?, ?, ?;", conn);
OleDbParameter Param = cmd.Parameters.Add("#PIParam", OleDbType.Integer);
ParametroId.Value = 3;
OleDbParameter Cons = cmd.Parameters.Add("#PICons", OleDbType.Integer);
Cons.Value = 2;
OleDbParameter Cte = cmd.Parameters.Add("#PICte", OleDbType.Integer);
Cte.Value = 1;
using ( OleDbDataReader reader = cmd.ExecuteReader() ){
if ( reader.HasRows && reader.Read() )
valor = (reader["VALUE"].ToString());
}
cm.ReleaseConnection(conn);
} catch( Exception ex ){
MessageBox.Show(ex.Message.ToString());
}