Reputation: 781
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
Upvotes: 2
Views: 1341
Reputation: 754200
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.
Upvotes: 6