Local Database won't show my programmaticaly added table - c#

I will go at a c# contest and I will need to work with databases offline, and they should work on every PC, so if someone copies my project and runs my program, everything will work the same.
I created a Local Database with Add - New Item and made my database.
My code
private void Form1_Load(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(Properties.Settings.Default.bazalocalaConnectionString);
con.Open();
SqlCeCommand com = new SqlCeCommand("select * from Tabela",con);
SqlCeDataReader r = com.ExecuteReader();
while (r.Read())
{
MessageBox.Show(r["nume"].ToString());
}
com = new SqlCeCommand("create table taby(id int identity(1,1) primary key,nume nvarchar(10),prenume nvarchar(10) )", con);
com.ExecuteNonQuery();
con.Close();
}
The problem i have is, that after I create my table, and close the program, my new table won't be there in my server explorer.. why is that?
Did i Did something wrong?
And if I work like this, will it work on every PC?
My connection string is auto generated by visual studio when I create my local database and it is
Data Source=|DataDirectory|\bazalocala.sdf

When you use |DataDirectory| and compile the program in Visual Studio, the Visual studio creates a temp database in the Debug folder which is different from your original database. That is why the added table doesn't show up in there, instead of |DataDirectory| use the actual address.

The substitution string |DataDirectory| is replaced by the directory where your program runs.
During a Visual Studio debugging session this directory is BIN\DEBUG (or x86 variant).
So your table is added in a database located in BIN\DEBUG folder, while your server explorer window has a connection that points to a database located in the project folder.
You could try to add another connection that points to the database in the BIN\DEBUG folder and you will be able to see your table.
If you run your program outside VS then you don't have this problem.
To complicate further the matter there is the property Copy to output directory for your SDF file. If this property is set to Copy Always, then every time you start a debug session your SDF file is copied from your project folder to the BIN\DEBUG folder effectively overwriting the file and the change you have made in the previous debug session. You should change this property to Copy if Newer

you can try like this
try
{
SqlCeConnection con = new SqlCeConnection(Properties.Settings.Default.bazalocalaConnectionString);
con.Open();
//
// The following code uses an SqlCommand based on the SqlConnection.
//
using (SqlCeCommandcommand = new SqlCeCommand("CREATE TABLE taby(id int identity(1,1) primary key,nume nvarchar(10),prenume nvarchar(10) );", con))
{
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

SqlCeConnection con = new SqlCeConnection("Data Source=K:/PROJECT LOCATION/Database1.sdf");
con.Open();
string x = "insert into TABLE(your columns) values (what values you want)";
SqlCeCommand cmd = new SqlCeCommand(x, con);
try
{
cmd.ExecuteNonQuery();
}
catch
{
MessageBox.Show(" Something is wrong","ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
con.Close();
I created a connection and gave it the full location of the database, NOT the one from the bin/debug. Then i opened the connection and wrote the string x to save that data in my database. I created a new command which i tested in a try-catch clause and finally i closed the connection.

Related

SQL Server insert problem. Data insert operation is successful but after closing the application and re open it that data can not be found [duplicate]

This question already has an answer here:
SQL command INSERT is working but the data not appear in table
(1 answer)
Closed 3 years ago.
I am trying to write a C# application which will have an attached database.
So I did an insert operation which is working perfectly and after insert operation I can see my data in my data grid view. But after closing the application, I saw that my data table is empty. So I reopened my application and the data grid view is also empty.
Here is my sample code :
Insert
private void button_create_Click(object sender, EventArgs e)
{
int id = 7;
string ConStr = ConfigurationManager.ConnectionStrings["Doctor_s_Assistant.Properties.Settings.DocAssistDBConnectionString"].ConnectionString;
SqlConnection offDBconnection = new SqlConnection(ConStr);
offDBconnection.Open();
string sqlCommand = "INSERT INTO Treatment_Template VALUES (#id, #t_name, #t_body, #t_advice)";
SqlCommand sql = new SqlCommand(sqlCommand, offDBconnection);
sql.Parameters.AddWithValue("#id",id);
sql.Parameters.AddWithValue("#t_name", textBox_temp_name.Text);
sql.Parameters.AddWithValue("#t_body", richTextBox_temp_body.Text);
sql.Parameters.AddWithValue("#t_advice", richTextBox_temp_advice.Text);
sql.ExecuteNonQuery();
offDBconnection.Close();
MessageBox.Show("New Template Created");
}
Preview data:
private void button_Load_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DocAssistDB.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Treatment_Template", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Thanks in advance
You're either looking in the wrong DB (you're looking in the MDF file in the project main folder alongside your csproj but the MDF your app altered is found in the BIN\DEBUG or BIN\RELEASE subfolder - the MDF was copied there during build)
Or
For your MDF file you have "copy to output folder" set to Copy Always so your build prices is always overwriting the MDF that your exe is editing (in the BIN\xxx subfolders) with a fresh blank database from the project folder
Click the MDF in Solution Explorer and set the copy option to Copy If Newer in the Properties window. Always make schema changes to the MDF in the project folder, not the bin folder. Be aware that when you make schema changes etc the file will become newer and overwrite your test data - if you want to keep the test data and other timings your program has written, copy the file back from bin folders first, then change the schema, then it will be copied out again during builds
Oh, by the way; check out http://dapper-tutorial.net - it will save you wasting your life writing tedious data access code; all that code you wrote in your post can be reduced to about 4 lines

C# Winform SQL Server Connection String

Working on a WinForm project making use of SQL Server.
Currently my MusicPlayerDB.mdf has its Copy to Output Directory property set to Copy if newer.
After I run my InsertIntoDB, I close the Winform and proceed to check the table over in Server Explorer. But is seems as my table wasn't updated. But if I go to check Bin/Debug and check MusicPlayerDB.mdf, the data is there.
What would be the best way to fix this? I've seen other comments saying to use the absolute path of the .mdf (or something along those lines), but I would like to avoid that if possible.
Here is my connection string,
private const String CONNECTION_STRING = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MusicPlayerDB.mdf;Integrated Security=True";
And here is my insert code:
private static void InsertIntoDB(List<string> userAccout)
{
String sqlQuery = "INSERT INTO dbo.UserAccount (UserName, UserPassword, PasswordQuestion, PasswordHint, PasswordKey) "
+ "VALUES (#UserName, #UserPassword, #PasswordQuestion, #PasswordHint, #PasswordKey);";
using(SqlConnection connection = new SqlConnection(CONNECTION_STRING))
{
connection.Open(); //open connection
using(SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// set up command
using(SqlTransaction trans = connection.BeginTransaction())
{
try
{
command.Connection = connection;
command.Transaction = trans;
command.Parameters.AddWithValue("#UserName", userAccout[0]);
command.Parameters.AddWithValue("#UserPassword", userAccout[1]);
command.Parameters.AddWithValue("#PasswordQuestion", userAccout[2]);
command.Parameters.AddWithValue("#PasswordHint", userAccout[3]);
command.Parameters.AddWithValue("#PasswordKey", Convert.ToInt32(userAccout[4]));
int r = command.ExecuteNonQuery(); //execute the command
trans.Commit();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message); //couldn't execute command
}
}
}
}
} //end of InsertIntoDB
This is how it is expected to work. |DataDirectory| in a desktop app point to where your executable runs. This means bin\debug or bin\release (the working folders) when you run the app inside VS but the installation folder when you run the app outside VS.
This arrangement allows you to keep your empty MDF in the project folder while a working copy stays in your output folders. When you need to change something in the schema of your database you use Server Explorer to change the copy in your project folder. So a new copy of the file will be copied in the output folders at the start of the next VS session. When you need to distribute your app you distribute the MDF file in your project folder.
Of course, if you need to check what happens in the working copy of your db then you can create a new connection inside Server Explorer that points to the MDF file in the working folders.
If you need more control then you can change where the substitution string |DataDirectory| points. See, for example, this Question and my answer there

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());
}

Can i make sql Database part of c# Project

I have made a sample c# application (First project ive done) Its quite a simple application which uses a database to store data and edit data.
The problem i am having is the program works perfectly fine on my computer but if i publish the application and put it on another computer it cannot use the database as it is not part of the project.
I used connection string
private SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\Ryan\\Documents\\Visual Studio 2015\\Projects\\youtubeLoginTut\\youtubeLoginTut\\data.mdf\"; Integrated Security = True; Connect Timeout = 30");
Which is obviously the path to the database on my computer and will not be the same on the next computer. Is there anyway i could include the database in the package so its referenced from where ever the application sits.
Ive tried shortening the path to for example ..\data.mdf but to no avail and i cant find anything on google so im all out of ideas.
Go easy im very new to c#
Cheers
Ryan
There is a way to get the location of your project in every computer : (inside the bin/debug/)
string path = AppDomain.CurrentDomain.BaseDirectory //example : C:/Users/Ryan/Documents/Visual Studio 2015/Projects/Youtubetut/bin/debug
you just need add the location of the database inside of the project's folder to this path. path will replace your "C:\Users\Ryan\Documents\Visual Studio 2015\Projects\youtubeLoginTut" and make sure to move your database inside the debug folder.
Afeter publiching your database with your project you get the Installtion Path From Deployment byuse :
string sourcePath =System.Reflection.Assembly.GetExecutingAssembly().Location
sourcePath =sourcePath +"\data.mdf";
If it's a simple application you can try to use embeded DB like SQLite. I use it in my application and it works fine.
If you want to use SQLite, let's go step by step.
download the dynamic library System.Data.SQLite.dll for your version of the .NET Framework
link System.Data.SQLite.dll to your project
write a code something like this
Create a table
SQLiteConnection con = new SQLiteConnection(String.Format(#"Data Source={0};Version=3;New=True;", "./db/mydatabase.sdb"));
con.Open();
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandText = #"CREATE TABLE Books (BookId int, BookName varchar(255), PRIMARY KEY (BookId));";
cmd.ExecuteNonQuery();
con.Close();
Read the data
using(SQLiteConnection con = new SQLiteConnection(String.Format(#"Data Source={0};Version=3;New=False;", "./db/mydatabase.sdb")) {
con.Open();
using (SQLiteCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"SELECT BookName FROM Books WHERE BookId=1 LIMIT 1;";
using (SQLiteDataReader reader = cmd.ExecuteReader()) {
if (reader.HasRows && reader.Read()) {
oResult = Convert.ToString(reader["BookName"]);
}
reader.Close();
}
}
con.Close();
}

SqlCommand cannot create table

I have a problem with creating a table with SqlCommand. The code is as follow
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="+ Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"\Database\Test.mdf;Integrated Security=True; Database=Test";
SqlConnection sc = new SqlConnection(cs);
sc.Open();
//SqlCommand cmd = new SqlCommand();
try
{
using (SqlCommand command = new SqlCommand(
"CREATE TABLE Dogs1 (Weight INT, Name TEXT, Breed TEXT)", sc))
{
Console.WriteLine(command.ExecuteNonQuery());
}
}
catch
{
Console.WriteLine("Table not created.");
}
I put the code in Main function and run it. There is no error and the database can be opened. However, when I check the database, there is no table created. Can anyone help to see what is wrong here? Thank you.
Thank you everyone. This problem has been solved. When I created Test.mdf, I actually created in the Database folder in the project. When I double clicked the Test.mdf, it was linked to Server Explorer in Visual Studio. Then when I changed the property to Copy Always, the Test.mdf will be copied to bin/Debug/Database/. When I used Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), I was actually operating the one in bin/Debug/, rather than the one in the project folder. As a result, it looks like the table was not created. So now I linked the Test.mdf in bin/Debug/Database to the Server Explorer, I can see new tables are created.
Yes, you have created the DB inside your project which will not be available in SQL Server Management studio because this is local application DB. The .mdf file location is different for the DB in SSMS.

Categories