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.
Related
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");
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.
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());
}
I am trying to connect database.sdf on same director. Using following code but gives me connection error. What I am doing wrong. Please help me.
Dim connstring As String
Dim con As SqlCeConnection
Dim command As SqlCeCommand
connstring = "Persist Security Info = False; Data Source = '.\database.sdf', Password = 'pswrd', File Mode = 'shared read'"
con = New SqlCeConnection
con.Open()
command = New SqlCeCommand("select * from users where Name=? and Password=?", con)
I think you're missing some code... or maybe that's the problem, you never bind your SqlCeConnection to connstring
Dim con As SqlCeConnection
Dim command As SqlCeCommand
con = New SqlCeConnection("Persist Security Info=False;Data Source=.\database.sdf;Password=pswrd;File Mode=shared read")
con.Open()
command = New SqlCeCommand("select * from users where Name=? and Password=?", con)
You do not need the single quotes (') in the different parts of the connection string, and you should be using a semi-colon (;) to separate the different values.
"Persist Security Info = False; Data Source = .\database.sdf; Password = pswrd; File Mode = shared read;"
Apart from that, you do not appear to be using the connection string in your code. You should be using it to open the connection:
con = New SqlCeConnection(connstring)
Check out Connection Strings for great connection string assitance.
It looks like your line:
connstring = "Persist Security Info = False; Data Source = '.\database.sdf', Password = 'pswrd', File Mode = 'shared read'"
is using both "," and ";" to separate the parameters. Update then all to use ";"
To query an excel sheet via SQL, I used to use either:
Dim excelConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties=""Excel 8.0;IMEX=1;HDR=YES;"""
or
Dim excelConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + strPath + ";Extended Properties=""Excel 12.0;IMEX=1;HDR=YES;"""
Now this worked fine until I installed Office 2010.
Now I get a
Microsoft.Ace.OLEDB.12.0 provider is not registered on this machine
exception.
How can I find out the correct connection string/provider?
I believe for Excel 2010 it is :
Dim excelConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Password="""";User ID=Admin;Data Source=D:\\MyDocs\\oledb.xlsx;Mode=Share Deny Write;Extended Properties=""HDR=YES;"";Jet OLEDB:Engine Type=37"
This appears to work in my visual studio, I got Excel to generate the query string and it had the extra entry in it.
I downloaded and installed Office System Driver: Data Connectivity Components as advised above - and the below code worked:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Password=\"\";User ID=Admin;Data Source=d:\\Sample.xlsx;Mode=Share Deny Write;Extended Properties=\"HDR=YES;\";Jet OLEDB:Engine Type=37";
OleDbConnection connection = new OleDbConnection(connectionString);
try
{
connection.Open();
OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", connection);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = command;
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception)
{
//throw;
}
finally
{
connection.Close();
}
Perhaps you uninstalled the Access Database Engine (ACE) components? They are still available for download from MSDN as 2007 Office System Driver: Data Connectivity Components.