I am working with .NET 4.5 and C# using a SQL Server Compact database.
Here is the insert command I am using:
try
{
conn.Open();
String query = "INSERT INTO categories (cat_title) VALUES (#cat_title)";
SqlCeCommand cmd = new SqlCeCommand(query, conn);
cmd.Parameters.AddWithValue("#cat_title", cat_title);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
After I do this, I immediately get results from the table to populate a combobox. I can see the newly added item.
However, when I go back to the Database Explorer, the items are not there. If I run the app again, I can see the item or items I added.
If I refresh the dB from the Database Explorer, the results are not longer present in the app.
Am I doing this right? Why would the results behave this way?
#marc_s and #ta.speot.is are correct, but for the other newbies out there I think I might also chime in.
The database that you see in the explorer is reading a different instance of the .sdf file than the one your connection string is referencing. It is possible that the explorer is reading the .sdf file from your main project directory, while your connection string is connecting to the .sdf file in you bin/debug/ folder. If this is the case, the .sdf file that your connection string references will be overwritten every time the program runs.
Related
I'm trying to copy all the data from my datatable into my database.
I'm using Microsoft SQL Server Database File as my database.
Here's the code I'm using,
private void button1_Click(object sender, EventArgs e)
{
connection.ConnectionString = connectionString;
connection.Open();
DataTable dt1 = new DataTable();
dt1 = ((DataTable)dataGridView1.DataSource).Copy();
SqlTransaction transaction = connection.BeginTransaction();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers,
transaction))
{
bulkCopy.DestinationTableName =
"dbo.StudentInfIns";
try
{
bulkCopy.WriteToServer(dt1);
transaction.Commit();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
Any idea as to why it won't go through?
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the transaction.Commit(); call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MainDB)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MainDB;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
I'm trying to write a C# application that restores many databases from .bak files placed in a certain folder. To do so I need the databases logical name from the files.
So I want to execute the following query :
RESTORE FILELISTONLY FROM DISK = N'C:\Folder\File'
The problem is: I can't get the result of this to my application, when I execute it in SQL Server Management Studio, it shows the name I want.
I tried to use ExecuteReader function from SqlDataReader but it doesn't return any data.
Can someone help me figure out how to get the result of queries like restore database, backup database into a variable in a C# application ?
Thanks in advance
The command RESTORE FILELISTONLY does return a result set as per the documentation RESTORE Statement - FILELISTONLY. What I did find during testing my code, you need to make sure the user that is running the application has permissions to read the specified file and directory. Otherwise you will run into issues.
For a code example of this:
var command = #"RESTORE FILELISTONLY FROM DISK = N'F:\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\Scratch.bak'";
using (var sqlConnection = new SqlConnection("Server=localhost;Database=Scratch;Trusted_Connection=True;"))
using (var sqlCommand = new SqlCommand(command, sqlConnection))
{
sqlConnection.Open();
var sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
Console.WriteLine($"Logical Name: {sqlDataReader["LogicalName"]}");
Console.WriteLine($"Physical Name: {sqlDataReader["PhysicalName"]}");
Console.WriteLine($"Type: {sqlDataReader["Type"]}");
}
}
You may also find that when trying to work SQL Server management, using the SqlConnection and SqlCommand objects may be more frustrating then they are worth. I strong recommend using the SQL Server Management Objects (SMO). This is actually what management studio uses when you are work with SQL Server. I have an example on GitHub if you are interested in it. Checkout GitHub: SMO Demo.
I create an application, which uses a local database, which is stored in the AppData folder. I created a DataContext to get the data:
private NorthWindDataContext northWindDataContext = new NorthWindDataContext(connectionString);
At each start of the application, it checks if the database exists. If it not exists, it should create the database:
DB:
if (!northWindDataContext.DatabaseExists())
{
try
{
northWindDataContext.CreateDatabase();
}
catch (Exception ex1)
{
try
{
northWindDataContext.DeleteDatabase();
}
catch (Exception ex2)
{
}
}
goto DB;
}
This works fine, but if I delete the file in the directory and start the application again I get the following Exeception, when it creates the database using CreateDatabase:
"Database 'C:\Users\me\AppData\Local\Test\Northwind.mdf' already exists. Choose a different database name."
If the CreateDatabase-method fails, it should delete the database (which actually not exists) using DeleteDatabase. Here is not an Exception thrown by the application. Then it should try to create the database again. Now the application doesn't throws the Exeception at CreateDatabase, but it is also not a database-file created.
This happens at each start of the application, if the database-file is deleted by the user, so what am I doing wrong or is there something missing?
The data context is using by default an instance of localdb ... deleting the database file (the .mdf file) doesn't mean that the database doesn't exist in this instance of localdb anymore. You can confirm that by deleting any .mdf file and querying the master database of the server
select * from sys.databases
You will find that the database already exists even after deleting the file , that's why you are getting the database exits error if you tried to create the database and probably the condition !northWindDataContext.DatabaseExists() won't be met cause localdb thinks it still has the db
I tried to open SQL Server Management Studio and delete the database from there then i got a file not found error and at this moment localdb noticed that the database has been removed and it has removed it from the object explorer and the sys.databases view
I'm recently new at C# and follow a tutorial on connection to the database, the connection for viewing or SELECT command was ok, I made some revision based on the threads of forums to make my code better, but when I was in INSERT for my SQL Server, I have some problems. I was able to insert the data but when I re-run the program the data that I just inserted earlier was not in the database.
Here is my code on insert
string commandText = "INSERT INTO loginInfo (name, pass, role) VALUES(#name, #pass, #role)";
using (connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#name", textBox1.Text);
command.Parameters.AddWithValue("#pass", textBox2.Text);
command.Parameters.AddWithValue("#role", textBox3.Text);
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch
{
}
finally
{
command.Connection.Close();
}
}
I'm trying to create a simple CRUD but not save the data... please help
If you're using the AttachDbFileName= clause in your connection string, you might have fallen victim to a well-known issue : you might just be looking at the wrong database (file) when checking your data.
When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the connection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The long-term viable solution in my opinion would be to:
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. YourDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
I need your help.. maybe it's the small task which I am not able to solve but I don't know how to search that on any search engine
I am using an .mdf file (vs 2103) in my WPF login register desktop application.. Everything is working fine, no compilation errors. I inserted some data into the .mdf file by using query in Visual Studio and then try to login through application and it's working fine. Moreover I am also able to register, i.e., insert into .mdf file from the register option of application if I use the "absolute path" of the .mdf file. Problem begins when I try to insert into .mdf file using a "relative path"... it doesn't insert data into the .mdf....I don't know why.
(this absolute path is not working. I have .mdf file in the database folder)
//connection string
connetionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database\Database1.mdf;Integrated Security=True";
//code
SqlCommand sqlCmd;
string sql = null;
SqlConnection sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sql = "insert into [NewTable] ( Name , Password ) values ('ABC' , '12345')";
sqlCmd = new SqlCommand(sql, sqlCnn);
sqlCmd.ExecuteNonQuery();
sqlCnn.Close();
MessageBox.Show("You have Been Registered");
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
It shows the message "You have Been Registered"
but is not visible in .mdf file...
I want to ask..why is it behaving like this....and I want to use the relative path as we cant judge the client system absolute path...what mistake I am doing? how to handle this (i guess self made) issue?
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand excellent blog article Bad habits to kick: Using AttachDbFileName for more in depth explanations and tips