I went through MSDN pages to learn ADO.Net using Commands. I am able to read using the sample code posted there.
But when I tried to use the modification code below, the insert is not happening. I am not ale to figure out why. Can someone please tell me what is wrong with this code?
string connectionString = "A_VALID_CONNECTION_STRING";
string commandText =
"INSERT INTO Contacts (FullName, Mobile) VALUES ('Pierce Brosnan', '1800-007')";
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
SqlCommand command = new SqlCommand(commandText, connection);
Console.WriteLine(command.ExecuteNonQuery());
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Edit
No exception is thrown.
The ExecuteNonQuery() which is supposed to return the no. of rows affected is returning 1.
Environment: Visual C# 2010 Express | SQL Server 2008 Express | Windows 7 Ultimate 32-bit.
Update
Previously I was using a MDF file present in the project. It was, I guess, automatically attached to the SQL server instance each time the project ran. This is when I had the problem. The connection string had some info about attaching a database file.
I removed the SQL Server 2008 Express that I installed along with Visual C# 2010 Express. Also removed the MDF file from the project.
I Separately downloaded and installed SQL Server 2008 Express along with Management Studio Express.
Created a new database in management studio.
Used a different type of connection string to use the database in the server.
Now INSERT is working!
P.S. I guess I should have mentioned that I had an attach database file scenario. Really sorry for that.
My suspicion is that you had the following scenario:
Database.mdf file was present in the project with the table structure created in it
Your connection string looked something like this Server=.\SQLExpress;AttachDbFilename=database.mdf;Database=dbname; Trusted_Connection=Yes;, i.e. loading the database in the connection string.
What was happening was, when you built/ran your project, your application was compiled and the database.mdf file was copied along with it to ApplicationProjectFolder\bin\Debug, so that when the application was run, the file database.mdf was present. This means that everytime you ran your project, the "empty" database.mdf file was copied from ApplicationProjectFolder\database.mdf to ApplicationProjectFolder\bin\Debug\database.mdf, hence the data "disappearing". Also, the file database.mdf probably had "Copy Always" set on its properties in the project.
So, the "INSERT" was working, it was just being "reset" everytime you ran your application.
Related
I'm using Entity Framework's Code-First and LocalDB, with the following connection string:
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyApp;Integrated Security=True;
Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False;MultipleActiveResultSets=true;
The instance and its database files were properly created inside this path:
C:\Users\Me\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB
But I was messing around and I renamed then deleted the MSSQLLocalDB through Visual Studio's "SQL Server Object Explorer" and its files. Now that I created it back, all databases generated via EF Code First are being created inside my %USERPROFILE% folder, i.e. C:\Users\Me.
In "SQL Server Object Explorer", if I right click and "Add New Database", it shows the right path. Right clicking the instance then properties shows that "Default Database Location" is correct.
The registry is correctly configured:
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Microsoft SQL Server\UserInstances\{9F44D466-A9BA-40E3-9DEA-21E0638C80A2}]
...
"DataDirectory"="C:\\Users\\Me\\AppData\\Local\\Microsoft\\Microsoft SQL Server Local DB\\Instances\\MSSQLLocalDB"
I tried to create a new instance through SqlLocalDB Utility with a different name, but it behaves the same way. Also tried rebooting, before and after deleting the instance, no success.
I also tried reinstalling. I uninstalled Visual Studio (Web and Desktop), MS Data Tools, MSSQL Compact and MS LocalDB, then reinstalled VS, but no success.
I don't want to change my connection string and point it to the correct path, since the project is shared and maintained by other developers.
How do I revert this behavior? I'm using Visual Studio 2015 Express.
You can set the path here (in registry):
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Microsoft SQL Server\UserInstances]
The path is not a part of your connection string, so do you really have a problem?
SqlCeConnection sqlCnn =
new SqlCeConnection(Properties.Settings.Default.mainDBConnectionString);
SqlCeCommand sqlCmd = new SqlCeCommand(
"INSERT INTO desktopItems (Location,Label) VALUES (#Location, #Label)",
sqlCnn);
sqlCnn.Open();
sqlCmd.Parameters.Add("#Location", openExe.FileName.ToString());
sqlCmd.Parameters.Add("#Label", openExe.SafeFileName.ToString());
sqlCmd.ExecuteNonQuery();
sqlCnn.Close();
I have this code but when I run the program, the database is not updating ...
Usually this scenario is caused by a simple error in visualizing the database.
Your INSERT works as expected, but you check if the insert succeded looking at a database in the wrong directory.
Using the DATADIRECTORY substitution string with a WinForms application means that, at debug time, your database is expected to be located in the directory BIN\DEBUG from your base project folder.
Visual Studio make sure that this is the case because in your project, the database file, is marked with the property Copy To The Output Directory set to Copy Always or Copy If Newer.
And it is here that the insert happens when you run your code inside a debug session of Visual Studio.
Then you check the result of the execution using the SERVER EXPLORER connection. But this connection points to the original database in the Project Folder and, of course, the new record is not present.
Usually the database in the project folder is kept up to date for the deployement, with the correct schema and initial data, but without any records that are inserted just for debug purpose.
So you could simply add a new connection to the SERVER EXPLORER pointing to the database in the BIN\DEBUG, rename it (like 'DEBUG-DB') and keep your original connection in case you need to change something in the schema of the database before releasing your application.
I am building a C# windows application using sql server 2005 and visual studio 2008.
To deploy the application on clients computer. I do this this in this order
I install the sql server 2005 with the same user/pass (ie sa/pass) i made in my app.
I run my windows application msi file. It install my databasae in sql server 2005.
when I try to run the application I fail due to different machine name and sql server instance name on my clients computer. i am getting error in connection string. i need a way to extract the target computername and sql server instance and save the same in my application setting during deployment (using in my c# code so that i can make a connection string at runtime.)
To resolve the problem what i am doing is I am installing visual studio on my client's computer and editing the source code to change the machine name and sql server instance. Then my windows application runs. I don't want to resolve my problem this way but rather need a way where i can set my parameters at deployment time or leave it up to you to suggest a better way.
I would request you to help me.
Google will give you lot of options. Have you followed the right steps while copying a database.
Follow these links http://blogs.msdn.com/b/sreekarm/archive/2009/09/11/move-a-database-from-one-server-to-another-server-in-sql-server-2008.aspx
and this will answer yours DBA Stack Exchange
Also post the Exact error message you get.It ll be useful to figure out the issue
Using SQL CE will require a lot of rework.
The full install order is:
Install Windows Installer 3.1 (if its not installed)
Install .Net 2.0 (if its not installed)
Check if SQL is NOT already installed:
HKLM "SOFTWARE\Microsoft\Microsoft SQL
Server\${instance_name}\MSSQLServer\CurrentVersion" "CurrentVersion"
Then you need to install SQL Server:
${installer_path}\SQLEXPR.exe -q /norebootchk /qn
reboot=ReallySuppress addlocal=all INSTANCENAME=${instance_name}
SAPWD=${password} SECURITYMODE=SQL SQLBROWSERAUTOSTART=1
SQLAUTOSTART=1 AGTAUTOSTART=1 ASAUTOSTART=0 RSAUTOSTART=0
DISABLENETWORKPROTOCOLS=0 ERRORREPORTING=1 SQMREPORTING=0 ENABLERANU=0
ADDUSERASADMIN=1
To connect to the SQL Server instance use your data link properties dialog. You will need to give clear instruction to your users how to connect to the instance. eg
If you use the .\Instance_Name syntax where the "." dot represents the client PCs name that should solve the problem. Also use this in your connection string.
So, if I understand you correctly, you have hardcoded your connection string inside your source code. And of course, you have discovered at your expense how this is really a bad idea.
You need to have that connection string saved in your app.config file. In this way, when you install your application to your customer, you need only to change the config file and your code is ready to go.
To insert your connection string in your app.config:
right click on your project and select Properties, then go to the
Settings page. This will create a settings.settings file for your
project and will open a GUI editor for your properties.
Now insert a string in the column name (for example
testConnection)
Select from the Type column the ConnectionString type
Insert, in the value column, a connection string valid for your
development machine
Now if you open the app.config you will notice a new section called ConnectionStrings that will look like this:
<connectionStrings>
<add name="ProjectName.Properties.Settings.testConnection" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\mytemp.mdb;User Id=admin;Password=;" />
</connectionStrings>
Now it is time to fix your code once and forever.
In every place where you have an hardcoded connection string replace that code with something like this
string constring = ConfigurationManager.ConnectionStrings["ProjectName.Properties.Settings.testConnection].ConnectionString;
And while we are here, check if the LocalDB version of SqlServer Express 2012 could be used to remove also the need to install SqlServer.
What is the easiest way to setup a test environment on my local machine using Visual Studio 2008 with a website that that has a mssql database, which is hosted through a webhost?
I am web designer and I am re-skinning a live website that is built in .NET C#. I have access to the files and when I run it in Visual Studio (localhost) only the static files are obviously pulling up , which is problematic for testing. I need to be able to run the entire website on my local. I am not going to be messing with the database at all, but I know that I am going to need it to be able to have a local copy that works. I am not extremely savvy on these types of things. I was hoping that someone could either point me in the right direction (ie. search terms, keywords) or give me some instructions on how to make this work. Any help is appreciated.
Thanks.
You should set up MSSQL server first. You can take backup from your production database using
RMC on DB -> Tasks -> Backup..
Then you use the generated .bak file on your local server to insert the copy of the database into your SQL Server instance like this:
RMC on Databases -> Restore Database -> Path to your backup..
At this step your instance should contain the database with all the tables and data. Next thing to do would be to change your web.config file connection string (or any place else, where the "Connection string" is set pointing the website to the database) accordingly to your instance. If it's MSSQLSERVER instance name, you can just use following connection string:
Data Source=(local);Initial Catalog=<database name>;Integrated Security=True;
After this compiling and running your source codes should be returning you the site in its fullest.
Hello people I've been struggling to use sqlite in my C#2.0 application and I have finally decided to get rid of assumptions and ask really basic questions.
When I created a database say iagency with table users, from external tools like firefox plugging and another sqladmin tool I can't query it from sqlicommand inside vs2005 it displays System.Data.SQLite.SQLiteException:Sqlite Error no such table users, please be assured that I've made reference to system.data.sqlite installed with SQLite-1.0.61.0-setup
When I do the opposite like create a database and a table from VS server explorer and VS database gui tools it can't be queried neither but can be seen by other tools, but tables created through query from VS using stringbuilder eg create table bla bla. it can be display in a datagrid but none of the tools can see and display that table.
WHAT DO I NEED EXACTLY TO MAKE SQLITE WORK IN MY APPLICATION?
I've tried to add sqlite3.dll of sqlitedll-3_6_14.zip downloaded from sqlite site under section precompiled binaries for windows as reference to my application but it fails with make sure it's accessible an it's a valid assembly or com component.
I downloaded this SQLite-1.0.61.0-setup.exe Ran the installation then I wrote this to access the firefox favorites sqlite db.
using System.Data.SQLite; // Dont forget to add this to your project references
// If the installation worked you should find it under
// the .Net tab of the "Add Reference"-dialog
namespace sqlite_test
{
class Program
{
static void Main(string[] args)
{
var path_to_db = #"C:\places.sqlite"; // copied here to avoid long path
SQLiteConnection sqlite_connection = new SQLiteConnection("Data Source=" + path_to_db + ";Version=3;New=True;Compress=True;");
SQLiteCommand sqlite_command = sqlite_connection.CreateCommand();
sqlite_connection.Open();
sqlite_command.CommandText = "select * from moz_places";
SQLiteDataReader sqlite_datareader = sqlite_command.ExecuteReader();
while (sqlite_datareader.Read())
{
// Prints out the url field from the table:
System.Console.WriteLine(sqlite_datareader["url"]);
}
}
}
}
Try opening up the database in the command line SQLite tool (from SQLite.org), and check the schema.
You can check the schema in this way:
.schema
This will dump out all the SQL necessary to create the tables in the database. Make sure the table is there, with the name you assume it should have.
You do not need the .dll file from SQLite.org, all you need is the assemblies from System.Data.SQLite.
For me - this link helped a lot at start.
Was harder to get subsonic work, to make database accessible through web application -
but that's another story.
You might try adding the location of the assembly and the db to the Path environment variable. The SQLite assembly contains both .Net and native code merged together, so you do not need the C dll. (the mergebin tool they include to do this is pretty interesting)
I also tried adding the location to Path environment variable but without success.
Finally I copied System.Data.SQLite.dll and System.Data.SQLite.lib into the bin folder of the Web application where other assemblies are located, and application worked.