I am completely new sql/database applications and am trying out a simple contact management applicaton using Visual Studio 2015 C#. I am using 'SQL Express LocalDB'. I have read on google that it is meant for development purpose, but microsoft also mentions that it could be used for production purpose too.
My problem is that when I try out the application from my developement system, the application first time takes few seconds to load but after that every query runs quickly. When I tried this on one my friends system, it takes time everytime I try to use any query. The database is just with 20-30 records.
I create new connection using 'new SqlConnection' and then execute command created by 'new SqlCommand' and after executing query I close the connection.
Here is the code snippet from my app
SqlConnection sqlConnection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = ""C:\ContactsDB.mdf""; Integrated Security = True; Connect Timeout = 30";);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlConnection;
sqlCmd.CommandText = "SELECT Id, first_name, last_name from ContactsMaster ORDER BY first_name";
sqlConnection.Open();
SqlDataReader reader = sqlCmd.ExecuteReader();
try
{
while (reader.Read())
{
ListViewItem lvi = new ListViewItem(reader["first_name"]);
listViewItems.Add(lvi);
lvi.SubItems.Add(reader[0].ToString());
}
}
finally
{
reader.Close();
}
sqlConnection.Close();
Q. Should I keep the connection open all the time while app is running? I don't think this should be suggested. As if app crashes database can get corrupt.
One of the backdrop which ppl saying that LocalDB closes the connection every new milliseconds. So should I keep pinging the database every few milliseconds? Or I should not use localdb in production at all?
I want to make the app such that the requirement goes really low regaridng the database prerequisites. Like LocalDB installation is really seamless.
I have not used SQL Server Express, does Express installation is also seamless like LocalDB and can I use the connection string like LocalDB in Express too, giving the .mdf filename directly?
localdb has auto shutdown. default is 5 min. you can set it to higher value (ie: 12hour).
max is 65535 min.
see: How to prevent SQL Server LocalDB auto shutdown?
also sqlexpress autoshutdown is 1hour if im not wrong.
symptoms on my pc:
first open is 10- 30 seconds slow. if i reopen app right after it is below 1 second. if i wait for a while it is slow again
There are many things to take in count for ddbb performance, it's not a simple question. For such small amount of records there shouldn't be performance problems. Try storing the ddbb files in another disk different from OS disk, and even better, place data file and log file in different disks too.
About your question, connections must be always closed and disposed properly in a finally block or inside a using block.
Sql Express is very easy to install, and also use a connection string, been the biggest difference that it can be used across the network.
Finally moved to SQLite and that is much faster in compare to SQLLocalDB.
Related
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'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.
The main issue I have is that a simple select from my SQL Server CE database has a typical wait time of 17 seconds for the first query and ~5 seconds for each subsequent query.
After letting the site sit idle for a couple minutes, the 17 second delay comes back. I am assuming the delay is from establishing connections, caching, etc, but I feel on our LAN this is a ridiculous wait and will only get worse for outside users.
The site is a c#/ASP.NET web site that is using a SQL Server Compact database (v4.0.8876.1). This is deployed to an IIS8 server. The site is intended to calculate values from user input using coefficients for different models that are stored in the database.
What am I doing wrong for there to be such a massive delay during the connection/queries?
Connection string:
<add name="DatabaseConnection"
connectionString="Data Source=|DataDirectory|\Database.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
Query:
string connstr = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
using (SqlCeConnection conn = new SqlCeConnection(connstr))
{
string queryString = #"Select id, description, imagePath
from ConservationModels
where model = #modelName";
SqlCeCommand command = new SqlCeCommand(queryString, conn);
command.Parameters.AddWithValue("#modelName", modelName);
try
{
conn.Open();
SqlCeDataReader reader = command.ExecuteReader();
while (reader.Read())
{
modelID = (int)reader[0];
description = (string)reader[1];
imagePath = (string)reader[2];
}
reader.Close();
}
catch (Exception ex)
{
throw;
}
}
Apologies for any missing information and I appreciate any suggestions. If there is a better way to achieve the goal for a web site, I am all ears.
This may be belated, but I recent found out (the hard way), that if you use SQL Server CE with ASP.NET on OWIN hosted on IIS, IIS will recompile or build a new app domain on every request. No idea why this happens, but the time you're seeing is likely to be ASP.NET rebuilding the application.
My application originally uses SQL Server Express with Entity Framework and everything works fine -- typical slow response on the first request as Entity Framework compiles the database schema, then lightning-fast afterwards. Static variables on the application carry across multiple requests.
I moved from SQL Server Express to SQL Server CE, and then suddenly I see Entity Framework recompiling the schema on every request. That means that every request is now slow.
Also, any static variables I keep on the application is reset for every request -- consistent with a new app domain being built.
Moving the whole stack unchanged to self-hosting on OWIN and suddenly it becomes normal again -- the first request slow, the subsequent ones lightning-fast.
This proves that ASP.NET on OWIN on IIS with SQL Server CE is doing something weird by not reusing existing threads and constantly building new app domains.
Following MatteoSp's advice, I removed SQL Server CE components from the site and created a SQL Server Express database to replace it. Though the compilation time on the site seems to have increased for some reason, this resolved my issue for the slow queries/connection.
Thank you for the assistance.
We have multiple DB servers. On one of the servers we have a master config table that holds instructions as to what DB server and DataBase name an Agency is supposed to use.
Currently each Database always has 2 connections on them, even if they're not being used (which we are fixing). However, we're trying to find a way to make it so our connections are not all over the place, and relieve some of the stress on our DB Servers.
After a lot of research we found some articles saying to do all connections to a central location, and then Change which database we're using through the SQLConnection object. Which seems a bit roundabout, but could work.
So I'm wondering what others do in this situation?
The current path for this is:
-User Logs in
-System access ConfigTable to find out which database user is going to connect to.
-System loads the Agency connection settings into memory (SEssion) for that user.
-Every request now directly hits that users database.
Is there a more efficient way of doing this?
Open connections late, and close them early.
For example:
string result;
using (var con = new SqlConnection(...))
{
con.Open();
var com = con.CreateCommand();
com.CommandText = "select 'hello world'";
result = com.ExecuteScalar();
}
The Windows OS will make sure to efficiently pool and reuse connections. And since you're only using connections when you need them, there are no idle connections lying around.
EDIT: Windows only caches connection strings that are literally the same, so if you use Initial Catalog=<dbname> in the connection string, that could hurt performance by requiring 500+ "connection pools" for one server.
So if you have 4 servers with a lot of databases, make sure you only use 4 connection strings. After connecting, switch database with:
com.CommandText = "use <dbname>";
com.ExecuteNonQuery();
Or query with a three-part name like:
select * from <dbname>.dbo.YourTable
I'm making an app that will be installed and run on multiple computers, my target is to make an empty local database file that is installed with the app and when user uses the app his database to be filled with the data from the app .
can you provide me with the following examples :
what do I need to do so my app can connect to its local database
how to execute a query with variables from the app for example how would you add to the database the following thing
String abc = "ABC";
String BBB = "Something longer than abc";
and etc
Edit ::
I am using a "local database" created from " add > new item > Local database" so how would i connect to that ? Sorry for the dumb question .. i have never used databases in .net
Depending on the needs you could also consider Sql CE. I'm sure that if you specified the database you're thinking of using, or your requirements if you're usure you would get proper and real examples of connection strings etc.
Edit: Here's code for SqlCe / Sql Compact
public void ConnectListAndSaveSQLCompactExample()
{
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\datafile.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
// Read all rows from the table test_table into a dataset (note, the adapter automatically opens the connection)
SqlCeDataAdapter adapter = new SqlCeDataAdapter("select * from test_table", connection);
DataSet data = new DataSet();
adapter.Fill(data);
// Add a row to the test_table (assume that table consists of a text column)
data.Tables[0].Rows.Add(new object[] { "New row added by code" });
// Save data back to the databasefile
adapter.Update(data);
// Close
connection.Close();
}
Remember to add a reference to System.Data.SqlServerCe
I'm not seeing anybody suggesting SQL Compact; it's similar to SQLite in that it doesn't require installation and tailors to the low-end database. It grew out of SQL Mobile and as such has a small footprint and limited feature-set, but if you're familiar with Microsoft's SQL offerings it should have some familiarity.
SQL Express is another option, but be aware that it requires a standalone installation and is a bit beefier than you might need for an applciation's local cache. That said it's also quite a bit more powerful than SQL Compact or SQLite.
Seems like you're:
-Making a C# app that will be installed and run on multiple
computers
-That needs a local database (I'm assuming an RDBMS)
-You need to generate a blank database at installation
-You then need to be able to connect to the database and populate it when
the app runs.
In general, it seems that you need to read up on using a small database engine for applications. I'd start by checking out SQLite, especially if you need multi-OS capability (eg., your C# program will run on Microsoft's .NET Framework and Novell's Mono). There are C# wrappers for accessing the SQLite database.
I believe this question is about the "Local Database" item template in Visual Studio:
What are you considering as a database? From what little you've provided in your question, I'd suggest SQLite.
You can get sample code from their site Sqlite.NET
Not sure I fully understand what you're asking but Sqlite is a good option for lightweight, locally deployed database persistence. Have a look here:
http://www.sqlite.org/
and here for an ADO.NET provider..
http://sqlite.phxsoftware.com/
For 1)
The easiest way to provide this functionality is through SQL Server Express User Instances. SQL Server Express is free, so your user does not have to pay additional license for SQL Server, and the User Instance is file-based, which suits your requirement.
For 2)
This is a big topic. You may want to go through some of the tutorials from Microsoft to get the feeling of how to connect to DB, etc.