I am using sql server 2008 R2 and sql server managment studio .
I want to attach the local database file at run time .
I provided the local database path via texbox to the connection string .
But it gives me error
invalid object name .
con = new SqlConnection("Data Source=
(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" + databasepathtextbox.Text + ";
Integrated Security=True; MultipleActiveResultSets =True;");
and command to insert data:
con.Open();
cmd=new SqlCommand(" insert into Firsttimecheck (checkfilepath)
Values('" + textBox1.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
And the path which i get via texbox as
D:\\data\\datainfo\\schoinfo\\Database1.mdf
Please help, how to add local database file path at run time?
Finnaly I figure out the error . The error was \\ I replace it with \ and it worked
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 have Added SslMode='none' part to the data source in the connection string since there was a MySQL exception called,
“The host localhost does not support SSL connections.”
I referred this solution in StackOverflow.
Solution
After that, the error was gone. But when I tried to Debug using step into in the 2nd iteration of the program there was an error,
The error triggers in bl.Load(); in the below code
library.WriteErrorLog("Update The Table");
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "TRUNCATE TABLE jobs";
comm.ExecuteNonQuery();
conn.Close();
library.WriteErrorLog("truncate Table");
bl.Load();
"The used command is not allowed with this MariaDB version"
The connection string is as follows:
string connStr = "data source=localhost; UID='13user';database='13shop';port=3306;password='123';SslMode='none'";
Any clue about this error?
I am trying to connect my app, developed in C# with a SQL Server database.
The program is done! It's a mobile app.
My database is on C:\ProgramFiles\MyAppName\MyDatabase.sdf
My code line is:
SqlConnection conn = new SqlConnection("server =" + iP.Text +"," + port.Text + ";integrated security=false;Initial Catalog=" + DB.Text + ";User ID=" + userName.Text + ";Password=" + Pass.Text + ";Trusted_Connection=False;");
iP.Text = my IP (102.168.XXX.XXX)
port.Text = 49214 or 1433
DB.Text = "MyDatabase.sdf"
userName.Text= "sa"
pass.Text= "MyPass"
But when I try to connect it, the app says:
er.Message = "El servidor SQL Server no existe o se ha denegado el acceso.
My server name is the same that my userName?
The application was made by someone else, I did nothing. But now I have to change some things and make it better. There is no manual
Any idea? I really don't know what to do
You are using Sql Server Compact Edition (SDF file) not Sql Server.
The classes needed to connect to this kind of database are different
SqlCeConnection conn = new SqlCeConnection(......)
The classes for Sql Server cannot parse correctly your connection string and you get the mentioned error. Of course, the classes for Sql Compact Edition require a reference to the appropriate DLL
System.Data.SqlServerCe.dll
and the appropriate using statement at the beginning of your code file
using System.Data.SqlServerCe;
As last note, the connection string for a SQL CE database is simply
"Data Source = MyDatabase.sdf; Password ='<pwd>'"
doesn't seem possible to pass a specific user. See connectionstrings.com
I want to detach the database from SQL Server 2005 from my C# code. I use the DROP query to detach. But it statements delete the file from my local system. I want to detach the database and copy that database in runtime.
First try to connect to the SQL Server without providing any database name,or path just like below:
ConnectionString = #"Data Source= YourDataSource ;Integrated Security=True;Connect Timeout=30";
Note:
YourDataSource can either be . or .\SQLEXPRESS or .\MSSQLSERVER or (local)\SQLEXPRESS or (localdb)\v11.0 or etc.
Then by using the following query, detach your database.
"ALTER DATABASE [your DB] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [your DB]";
Ok.
My Sample code:
sql_connect1.ConnectionString = #"Data Source=.\sqlexpress;Integrated Security=True;Connect Timeout=30";
sql_command.CommandText = "ALTER DATABASE [IRAN] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [IRAN]";
sql_command.Connection = sql_connect1;
sql_connect1.Open();
sql_command.ExecuteNonQuery();
sql_connect1.Close();
The SQL Server SMO API let's you do anything Sql Server management studio can do (from c# code).
Check out this link
http://msdn.microsoft.com/en-us/library/ms162175.aspx
you can detach a database on SqlServer by the following code:
There is a stored procedure in SqlServedr 'sp_detach_db' for detach a database, has one argument DataBaseName. Here in the code 'MyDatabase' is the database name you should change it with your database name
// C# Code
SqlConnection conn = new SqlConnection("Server=(local); Data Source=;Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand("", conn);
cmd.CommandText = "sys.sp_detach_db MyDatabase";
conn.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Dispose();
You can use stored procedures for your problem. following link can be useful:
http://msdn.microsoft.com/en-us/library/aa259611.aspx
Myo Thu's comments lead me in the right direction, so here's a summary of steps on how to detach the database.
Step 1: Reference the following DLL's in your project [Reference]:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.SqlEnum.dll
Step 2: using:
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
Step 3: Code
var server = new Server(new ServerConnection(#"MyMachine\SQL2012"));
// Ensure database is not in use
server.KillAllProcesses("TestDatabase");
server.DetachDatabase("TestDatabase", true);
EDIT: Now documented in my blog here
In my C# application, I do the following:
using (SqlConnection connection = new SqlConnection(connectionstr))
{
connection.Open();
SqlCommand com1 = new SqlCommand("insert into Anfangstierbestand(bestand, jahr, loginid) VALUES (" + bestand + ", " + jahr + ", " + loginid + ");", connection);
SqlCommand com2 = new SqlCommand("select * from Anfangstierbestand;", connection);
com1.Connection = connection;
int ferksum = 0;
com1.ExecuteNonQuery();
connection.Close();
connection.Open();
SqlDataReader read = com2.ExecuteReader();
while (read.Read())
{
ferksum += Convert.ToInt32(read[2]);
}
// MessageBox.Show("Fehler beim Erstellen des Tierbestandes", "Fehler"); }
MessageBox.Show(ferksum.ToString());
}
It's a simple insert to a database. I added com2 to check, if the insert works.
Unfortunately, the the value of com2 tells me, that it works, but when I go to the Server Explorer and press Execute SQL, there are no new values.
I don´t know the reason. The code above is just an example, since a few days, no insert works anymore(before, the same code works).
Does anybody know what the reason can be?
EDIT:
C#:
string connectionstr = "Data Source=.\\SQLEXPRESS;" + "AttachDbFilename=|DataDirectory|\\Datenbank\\FarmersCalc.mdf;" + "Integrated Security=True;" + "User Instance=true;";
EDIT2:
Server Explorer:
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\user\Desktop\Farmer´s Calc\Programmierung\WPF\Finanz_WPF\Finanz_WPF\Datenbank\FarmersCalc.mdf";Integrated Security=True;User Instance=True
EDIT3:
Here are the columns:
id int,
jahr int,
anzahl int,
loginid int
EDIT4:
Is it possible that it´s a problem that I opened my project with expression blend? Normally, I work with VS 2010...
EDIT5:
Even because I can not answer my question(<100 reputations) I write it here:
Shame on me. Some of you were right, it was the wrong database-file. But I´m still wondering, why this happened, because I did not change anything since a few days and before this, it worked!
Thanks to all for helping!
You're using user instances, why? Isn't it possible that the instance you're connecting to in Server Explorer is not the same as the instance where your app is inserting data? What happens when you select data from within the app, does it reflect your insert(s)? It seems to me based on your connection strings that these are two completely different MDF files - they have the same name but they are in different locations.
Is the issue implicit transactions? Do you need to issue a commit of the SQL Insert? If com2 tells you that it's there then it may only see it since it's in the context of the current SQL transaction.
You should share your connection string for both Server Explorer and your SqlConnection (connectionstr). Ensure that you setup your Server Explorer connection with User Instance=true;.
As a diagnostic,
connection.Open();
int n = com1.ExecuteNonQuery();
// log or show 'n' , the nr of rows affected
Edit, after seeing the connectionstrings:
local db files in |DataDirectory|\ are very prone to be overwritten by the next run or build command.
Make sure you set them to 'copy never' or 'copy if newer' in the VS Solution explorer.
Perhaps somewhere in the callstack above this code, someone has added a TransactionScope.
This would cause the connections to enroll automatically in the transaction, and the connections could see the data inserted via that not-yet-committed transaction. When the scope is exitted without calling scope.Complete, the transaction gets rolled back and no data is saved.