SqlCommand cannot create table - c#

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.

Related

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

MSSQL delete code in visual studio with c# is running, but when I restart it returns to its original state

In my c # project that I work with local db, I need to clear the table. I can view the table that I cleared while the program is running, but when I restart it, it returns to its original state.However, I do not experience it problem when adding to my Sql table.i dont understand.Is there anyone who can help me?
SqlConnection SqlConn = new SqlConnection(#"Data Source = (Localdb)\MSSQLLocalDB; AttachDbFilename=" +
Directory.GetCurrentDirectory() + #"\HtbTs.mdf;" +
"Integrated Security=SSPI;Connect Timeout=30;User Instance=False");
SqlConn.Open();
string Delete = "DELETE FROM BagenTablo";
SqlCommand komut = new SqlCommand(Delete, SqlConn);
komut.ExecuteNonQuery();
SqlConn.Close();
If the original db in your project has a data so every time when you build your project or debug it the visual studio copy the original db file into output folder
you can open MDF file in your project and right click on db in server window, then click New Query
type and execute this query
TRUNCATE TABLE BagenTablo

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

Insert Into local database C#

I can't Insert and select from Local database data in C#.
I've read these articles
C# - Writing data in local database
http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection(v=vs.100).aspx
How to add local database items into textBox using listBox in C#
All the code samples are the same, here's my sample.
SqlCeConnection conn = new SqlCeConnection(#"Data Source=|DataDirectory|\PacjenciDB.sdf");
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText="INSERT INTO pacjenci (nazwiskoimie,adres,skierowany,opis) values (#nazwiskoimie,#adres,#skierowany,#opis)";
cmd.Parameters.AddWithValue("#nazwiskoimie", txtnazwiskoimie.Text);
cmd.Parameters.AddWithValue("#adres", txtadres.Text);
cmd.Parameters.AddWithValue("#skierowany", txtskierowany.Text);
cmd.Parameters.AddWithValue("#opis", txtopis.Text);
cmd.ExecuteNonQuery();
conn.Close();
Can someone tell me what I'm doing wrong?
I've tried tons of samples about insert data, but it doesn't work.
I can manage .MDF, but .SDF seems quite problematic.
Hope you help me
Ok, I'm going to take a guess here. Is the PacjenciDB.sdf included into Visual Studio project by any chance? Do you have the property "Copy to output folder" set to "Always" or something similar? It seems that every time you do a build you could be overwriting your output folder database file. Try putting the database in a folder that is not inside VS project.
BTW, your code is OK.
Look for a copy of the database with data in your bin/debug folder.
Solution is to not use |DataDirectory|, but use full path instead.
The above code is correct and most likely the problem is somewhere else, where you call that code from. If there is a problem with db connection or data is wrong - you should get an exception. Since there is no error occurred and no new records added - the code is not executed at all.
P.S.
.sdf is a Sql Server Compact Local Database, so using System.Data.SqlServerCe is correct
http://msdn.microsoft.com/en-us/library/system.data.sqlserverce(v=vs.100).aspx
Try using double backslash when setting the path to your database file:
string dbPath + "Data Source=C:\\DataDirectory\\PacjenciDB.sdf";
SqlCeConnection conn = new SqlCeConnection(dbPath);
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText="INSERT INTO pacjenci (nazwiskoimie,adres,skierowany,opis) values (#nazwiskoimie,#adres,#skierowany,#opis)";
cmd.Parameters.AddWithValue("#nazwiskoimie", txtnazwiskoimie.Text);
cmd.Parameters.AddWithValue("#adres", txtadres.Text);
cmd.Parameters.AddWithValue("#skierowany", txtskierowany.Text);
cmd.Parameters.AddWithValue("#opis", txtopis.Text);
cmd.ExecuteNonQuery();
conn.Close();

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