Can i make sql Database part of c# Project - c#

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

Related

The application built in C# cannot connect to the SQLlite database when it is published

I am new to C#, I built an application with a SQLITE database, which works fine on my computer, but it does work when I publish it and try it on another computer. It's impossible to connect to the SQL database.
I have searched plenty, on many forums, in French and English, but without success
so gar.
Here is my C# code
SQLiteConnectionStringBuilder SQLCSB = new SQLiteConnectionStringBuilder();
SQLCSB.DataSource = #"C:\Users\Moi\source\repos\projetcsharp2\bases_de_donnees\base_exemple.db";
string ConnectionString = SQLCSB.ToString();
SQLiteConnection SQLC = new SQLiteConnection(ConnectionString);
SQLC.Open();
SQLiteCommand SQLCmd = SQLC.CreateCommand();
SQLCmd.CommandText = "SELECT ref,titre FROM table_choses";
SQLiteDataReader SQLDReader = SQLCmd.ExecuteReader();
while (SQLDReader.Read())
{
// some results
}
SQLC.Close();
How can I do it?
I know I should change the path, but I don't know how to do it.
Thanks in advance for your help
Thanks for the answers
in fact I know it is a problem with the file location
The question: how to use relative path?
The database will not be created by the program, it is a collecton of songs lyricks.
Thanks again

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

C# mdf local database

I googled for half a day how to set the path of my database so if I put it on an other computer it will work. I would keep googling but I really need the answer really fast... I'll have to use it to a competition in few hours.
string path = Path.Combine(Application.StartupPath, "Database1.mdf");
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + path + ";");
conn.Open();
SqlCommand command = new SqlCommand("SELECT NAME FROM DATA", conn);
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string text = reader.GetString(0);
MessageBox.Show(text);
}
SqlCommand c = new SqlCommand("INSERT INTO DATA (id, name) VALUES(i, v)", conn);
c.Parameters.AddWithValue("#i", 1);
c.Parameters.AddWithValue("#v", "Jack");
c.ExecuteNonQuery();
conn.Dispose();
This code is working for selection but not for insertion. Then I hardcoded the path into:
String s = #"C:\Users\Radu\Documents\Visual Studio 2013\Projects\WindowsFormsApplication7\WindowsFormsApplication7\Database1.mdf";
and it works for both so it's not the SQL statement that is wrong.
So my question is: what is the path I should put into my SqlConnection object so that when they get my source code on my competition and test it on another pc it will work.
LocalDB is meant exclusively for development. You cannot use it in production. In your case, 'production' means the competition. Unless the competition organizer specifies that they support a SQL Server instance for you to connect to, and give out the connection parameters (ie. very unlikely), you shouldn't use use SQL Server in your project.
You can put the MDF file on any file share that your computer has access to. Just alter the path variable to point at the correct file share.
See answers to your question here Can SQL Server Express LocalDB be connected to remotely?

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.

Local Database won't show my programmaticaly added table

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.

Categories