Not inserting data into database and not getting any error - c#

I am not sure what I am doing wrong, If I use the connection string shown here, my application works fine.
SqlConnection conn = new SqlConnection();
string DbPath = Application.StartupPath;
DbPath = DbPath.Substring(0, DbPath.LastIndexOf("\\bin"));
DbPath = DbPath + "\\MyDatabase.mdf";
conn.ConnectionString = "Data Source=.\\EXPRESS2008;AttachDbFilename=" + DbPath + ";Integrated Security=True;User Instance=True";
but if I use connection string here, it's not inserting data into MyDatabase table
conn.ConnectionString = Properties.Settings.Default.MyDatabaseConnectionString;
My app.config is
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="ERPSystem.Properties.Settings.MyDatabaseConnectionString"
connectionString="Data Source=.\EXPRESS2008; AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated
Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
INSERT statement and preceding code:
comm = new SqlCommand("CreateUser", MyConnection.MyConn("Open"));
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("#UserName", SqlDbType.VarChar).Value = userName.Text;
comm.Parameters.Add("#Password", SqlDbType.VarChar).Value = userPassword.Text;
comm.Parameters.Add("#UserRole", SqlDbType.VarChar).Value = UserRole.SelectedItem.ToString();
comm.ExecuteNonQuery();
This is the code to get the connection
class MyConnection
{
public static SqlConnection MyConn(string str)
{
SqlConnection conn = new SqlConnection();
try
{
//get application path
string DbPath = Application.StartupPath;
if (Program.RunFrEn == true) //bool var
//remove string after bin folder
DbPath = DbPath.Substring(0, DbPath.LastIndexOf("\\bin"));
//add database name with new path
DbPath = DbPath + "\\MyDatabase.mdf";
//generate new connection string for database
conn.ConnectionString = "Data Source=.\\EXPRESS2008;AttachDbFilename="
+ DbPath
+ ";Integrated Security=True;User Instance=True";
//conn.ConnectionString = Properties.Settings.Default.MyDatabaseConnectionString;
if (str == "Open")
{
if (conn.State == ConnectionState.Closed)
conn.Open();
}
else
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return conn;
}
}
I am not getting any error
Thank you

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's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.

I also had fighted long time with same problem. And I saw many same questions & answers.
You're using |DataDirectory|. I assume you can get values from the DB file and you don't get error to run insert command but the values are not inserted into the DB file.
This is absolutely my private idea and my private conclusion is that this behavior is normal as |DataDirectory| does. I mean a data file of an application should be protected from manipulation once after deployment. The 'Data' file should provide data inside the file so that we can read the data.
Therefore, I coded to create a localDB .MDF file (SQL Server 2014) from users' side so that my applications can utilize the localDB to write and read data. My application automatically downloads data from cloud server which are we need to update frequently. On the other side, I put big and already fixed data into |DataDirectory| .MDF file, I mean inserted big data for read only and add the .MDF file to my project before deployment.
Hope my experience helps.. But, please keep in mind again that this is really my private opinion and I might be totally wrong and my experience is limited only to localDB. But again, I couldn't find a Microsoft's official document mentioning this behavior.
Do you have only 1 option like |DataDirectory|? Did this work to insert before? Is this code by you wrote on your own? If possible, try to find another option rather than |DataDirectory| to connect to the SQL Server database. I use a cloud SQL server with IP address but I can't understand why you use |DataDirectory|. There might be many various options as connection strings to SQL Server Express.

Related

Insert integer value into SQL Server database from C#

I am trying to insert an integer value into a SQL Server database as below when I run the program there are no any errors, but the table doesn't get updated with values. I have searched on the internet and I am doing the same can anyone help to find what I am doing wrong.
Note: I already defined "connectionString" as a string on the form class
private void btnUpdate_Click(object sender, EventArgs e)
{
int totalincome=600;
int totaldeductions = 10;
connectionString = ConfigurationManager.ConnectionStrings["BudgetApp.Properties.Settings.MainDataBaseConnectionString"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand("INSERT INTO Totals(TotalIncome, TotalDeductions) VALUES (#TotalIncome, #TotalDeductions)", con);
cmd.Parameters.AddWithValue("#TotalIncome", totalincome);
cmd.Parameters.AddWithValue("#TotalDeductions", totaldeductions);
cmd.ExecuteNonQuery();
MessageBox.Show("Done !!");
}
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. MainDataBase)
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=MainDataBase;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.
Code Seems correct,Perhaps you are checking the wrong DB?. I would add a Try/catch for exceptions. And remember to close connection after executing query. Regards
check your database column datatype,use try catch.
and try to replace cmd.Parameters.AddWithValue("#TotalIncome", totalincome); to cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totalincome;
try
{
int totalincome=600;
int totaldeductions = 10;
connectionString = ConfigurationManager.ConnectionStrings["BudgetApp.Properties.Settings.MainDataBaseConnectionString"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand(#"INSERT INTO Totals(TotalIncome, TotalDeductions) VALUES (#TotalIncome, #TotalDeductions)", con);
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totalincome;
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totaldeductions;
//cmd.Parameters.AddWithValue("#TotalIncome", totalincome);
//cmd.Parameters.AddWithValue("#TotalDeductions", totaldeductions);
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}

Data does not show in server explorer database after inserting new values

I created a backup form with this code:
private void btnBackUp_Click(object sender, EventArgs e) //Backup will work only when we place |DataDirectory| in our appconfig file
{
try
{
progressBar1.Visible = true;
progressBar1.Value = 15;
bool bBackUpStatus = true;
Cursor.Current = Cursors.WaitCursor;
if (Directory.Exists(#"D:\Backup_MAConvent"))
{
if (File.Exists(#"D:\Backup_MAConvent\MAConvent_Backup.bak"))
{
if (MessageBox.Show(#"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
File.Delete(#"D:\Backup_MAConvent\MAConvent_Backup.bak");
}
else
bBackUpStatus = false;
}
}
else
Directory.CreateDirectory(#"D:\Backup_MAConvent");
if (bBackUpStatus)
{
con.Open();
progressBar1.Value = 25;
string path1 = System.IO.Path.GetFullPath(#"SchoolDatabase.mdf");
SqlCommand cmd2 = new SqlCommand("backup database [" + path1 + #"] to disk ='D:\Backup_MAConvent\MAConvent_Backup.bak' with init,stats=10", con);
cmd2.ExecuteNonQuery();
progressBar1.Value = 35;
con.Close();
timer1.Start();
MessageBox.Show("Backup of the Database saved Successfully", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
timer1.Stop();
progressBar1.Value = 10;
progressBar1.Visible = false;
}
}
catch
{
MessageBox.Show(#"Backup Error, Please close the software & restart and then try again to backup", "Backup", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
This code was not working with the connection string of \bin database. So, I changed my connection string in app.config to |DataDirectory|
<connectionStrings>
<add name="SchoolManagement.Properties.Settings.SchoolDatabaseConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\SchoolDatabase.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
After that, when I was inserting new values to the database, the values were temporary showing in my search form having search query. But after stopping debugging the data was not in the database.
And then I changed Copy To output directory to copy if newer . so, now the data is showing on form's search gridview every time but it is not showing in the server explorer's database(show table data).
I know this problem is occurred due to the |Data directory| database and \bin database. Please suggest what to do? If I changed my connection string to the \bin database, all works well but backup code does not work. Please help if somebody knows the way to sort out this. Thank you
The whole User Instance and 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. SchoolDatabase)
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=SchoolDatabase;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.

Connection to SQL Server Database inside Visual Studio 2012 C#

Forgive me if this is easy and I have seen similar posts but I am new-ish to C# and have been struggling on this, so any help would be much appreciated.
I am trying to connect to a local DB SQL Server in Visual Studio 2012 but so far have had no luck.
I got my connection string from the properties of my local DB which in the picture is in the left hand pane.
public void connection()
{
string connectionString = "Data Source=(localdb)\v11.0;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";
SqlConnection con = new SqlConnection(connectionString);
try
{
con.Open();
lblConnectionTest.Text = "Connected successfully";
}
catch (SqlException ex)
{
lblConnectionTest.Text = ex.Message;
}
}
At this point, all I am trying to do is establish a connection to the DB and basically write out "connection successful" etc if it connects.
Currently with what I have, I receive the following error:
A network-related or instance-specific error occurred
while establishing a connection to SQL Server.
The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server
is configured to allow remote connections.
(provider: Named Pipes Provider, error: 40 -
Could not open a connection to SQL Server)
What am I doing wrong here?
Many thanks!
Firstly i suggest you to set conenction string in your config file.
link : http://msdn.microsoft.com/fr-fr/library/ms254494(v=vs.110).aspx
Second subject, best practise set your connection in using bloc
link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx
DataSource is your target sql server, access properties of your server and get name, but for your case i think that you want access remotly, so ensure that your firewall server is configured to allow.
If you are in C#, you can create an application config file (App.config), which will be having the connection string with its name.
this is sample code in the app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="myConnString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\AppsTest\Nov17RoomBooking\dbRoomBooking.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Then Your code should look like this:
private static string sqlConnectionString = ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString;
private void DeletingDataBase()
{
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
string sqlQuery = "SELECT, INSERT, UPDATE, DELETE";
cmd.Connection = sqlConn;
cmd.CommandText = sqlQuery;
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
catch { }
finally
{
cmd.Connection.Close();
}
}
}
}
I encourage you to start learning LINQ to SQL. In my opinion it's the better way for handling data and interacting with the database. I see you're trying to connect to MySql, but i really don't know if that's possible while using LINQ. I hope someone answers this question.
You can actually solve all of this with few clicks, im using visual studio 2012 and by pulling my ms sql table to the aspx file it actually forms the table on its own and even builds all the connection strings for you.
Your Connection String is wrong.
Correct Syntax for MS SQL SERVER 2012 Express (Built in )
lets suppose my DataBase File is at the path :
C:\Users\Zohair\Documents\Visual Studio 2012\Projects\Learning2\Learning2\Sample.mdf
My Connection String will be :
SqlConnection conn = new SqlConnection("Data Source=(localdb)\\v11.0;Integrated Security=true;AttachDbFileName=C:\\Users\\Zohair\\Documents\\Visual Studio 2012\\Projects\\Learning2\\Learning2\\Sample.mdf");
NOTE: If it gives an error when using single slashes (\) then replace them with double slashes (\\)

connecting to an SQL Server database

I've recently started programming asp.net with C# (using VS2008) and I wrote my first web application that connects to a database. First version worked ok but now there are some problems once I modify it. I'm giving the examples below which will depict the situation:
1) Works OK. Program connects to a database and uses a function DeleteAllRecords() to perform an action on it; important to note that I created the database to connect to in SQL Server Management Studio.
Code behind page of the button-click event handler:
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("przemek8");
SqlCommand myCommand = new SqlCommand("DELETE FROM table8", dbConnection);
myCommand.ExecuteNonQuery();
}
catch (SqlException exception)
{
Response.Write("<p>Error code " + exception.Number + ": " + exception.Message + "</p>");
}
dbConnection.Close();
}
2) the second time I didn't use the database made in SQL SM Studio but I added a new database element from Visual Studio itself (Website -> Add New Item). I added some fields to that database and I also configured a GridView to show the database which is working. The problem, however, is that when I want to connect the Gridview to the database created before in SQL SM Studio, it doesn't work - when configuring the connection it won;t let choose the database file, saying:
You don't have permission to open this file. Contact the owner or an administrator to obtain permission.
It seems to me that the reason for that may be trivial but I cannot sort it out.
Just to note that all that database files were created SQL SM Studio in its default destination on disc C.
3) Not being able to connect with the GridView to the database created by SQL Server I continued working with the database added by Visual Studio itself. It was working with the GridView so I used the function to interact with it (delete all the records) - the same that was used at point 1) but with database now.
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename='D:\\WebSite1\\App_Data\\mydtb.mdf'; Integrated Security=true; User Instance=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("mydtb");
SqlCommand myCommand = new SqlCommand("DELETE FROM Table1", dbConnection);
myCommand.ExecuteNonQuery();
}
catch (SqlException exception)
{
Response.Write("<p>Error code " + exception.Number + ": " + exception.Message + "</p>");
}
dbConnection.Close();
It does not connect to that one and the error message is:
Error code 911: Database 'mydtb' does not exist. Make sure that the name is entered correctly.
I'm new in this field, but should the data source in this case (connecting to the database created in Visual Studio) be Data Source=.\\SQLEXPRESS; as it is when the database is created in SQL Server Management Studio?
Thanks a lot for any help and suggestions!
asp.net excited beginner:-)
The problem your having with regards to connecting to the database on a server is because of
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
The best way to do this is to go to your Web.config file and find the block and add a connection to your database in there.
eg
<add name="ConnectionString" connectionString="Data Source=YOUR SERVER;Initial Catalog=YOUR DATABASE;User ID=YOUR USER ID;Password=YOUR PASSWORD" />
then you can just call the connection string accross your whole project whenever you need to use it.
Also with regards to VS2012. There are very few companies using that IDE at the moment so your probably better off learning VS 2010 in the most part but i would agree that VS2008 is fairly out of date now
i think this will help
SqlConnection dbConnection = new SqlConnection("Data
Source=.\\SQLEXPRESS;Integrated Security=true; initial
catalog=database name; uid=servername ; password=yourpassword");

How to backup from .mdf database that I created

I created a .mdf database file with Visual Studio 2008. I can retrieve and insert data into database but when I want to backup I receive an error.
My code:
string con = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|C:\test\Data|\DB.mdf;Integrated Security=True;User Instance=True";
connect = new SqlConnection(con);
connect.Open();
SqlCommand command = new SqlCommand(#"backup database [" + System.Windows.Forms.Application.StartupPath + "\\Data\\DB.mdf] to disk ='"+str+"' with init,stats=10",connect);
command.ExecuteNonQuery();
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
The error is:
error : invalid value for key 'attachdbfilename'.
Seems like your connection string is incorrect.
Try this one:
string con = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\test\Data\DB.mdf;Integrated Security=True;User Instance=True";
For more options, have a look at: http://www.connectionstrings.com/sql-server-2005
This is for SQL Server 2012 and .NET 4.0.1 only.
If you have those, you should be able to use AttachDbFilename.
Anyway, if you have an .MDF for embedded database and the instance is not running, you can just copy .MDF and .LDF to back up.
just use your connection string as
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["<your connection string name from your app.config file>"].ConnectionString);
i tried it and it worked for me.

Categories