简体   繁体   中英

How to run non-persistent queries in Visual Studio

When using the Query Design feature in Visual Studio, any queries that I run on a SQL Database or Microsoft Access Database while testing are persistent. Meaning they actually change the data in the table(s). Is there a way to make the queries non-persistent while testing them until a program is run? Using C# as a programming language, and .NET as a framework if it matters. Also need to know the process for doing this with either an MS Access or SQL database.

You can do transactions in C# similar to how you use them in SQL. Here is an example:

connection.Open();

SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;

// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");

//Execute query here
Query details

//check if test environment
bool testEnvironment = SomeConfigFile.property("testEnvironment");
if (!testEnvironment) {
   transaction.Commit();
} else {
   transaction.Rollback();
}

Here is the documentation on transactions in C#: https://msdn.microsoft.com/en-us/library/86773566%28v=vs.110%29.aspx

It should be possible for VS to create you a local copy of the SQL data you're working on while you're testing. This is held in the bin folder. Have a look at this:

https://msdn.microsoft.com/en-us/library/ms246989.aspx

Once you're finished testing you could simply change it to be pointing to the database you want to alter with your application.

I'm not aware of a way to get exactly what you're asking for, but I think there is an approach to get close to the behaviour you want:

When using Microsoft SQL Server, creating a table with a leading hash in the name (#tableName) will cause the table to be disposed of when your session ends.

One way you could take advantage of this to get your desired behaviour is to copy your working table into a temporary table, and work on the temporary table instead of the live table.

To do so, use something like the following:

SELECT * INTO #tempTable FROM liveTable

This will create a complete copy of your liveTable, with all of the same columns and rows. Once you are finished, the table will be automatically dropped and no permanent changes will have been made.

This can also useful for a series of queries which you execute on the same subset of a large data set. Selecting the subset of data into a smaller temporary table can make subsequent queries much faster than if you had to select from the full data set repeatedly.

Just keep in mind that as soon as your connection closes, all the data goes with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM