C# mdf local database - c#

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?

Related

Issue with connecting to SQL Server database from Visual Studio

I've created a simple Windows Forms application in C# and now find it hard to connect it to a SQL Server database. I've created the database within Visual Studio itself. However, once I try to insert data I get a SQL exception. My guess is there is problem in the connection data source i.e the con variable. Please help me find a solution.
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;Initial Catalog=Database1;Integrated Security=SSPI");
SqlCommand cmd;
SqlDataAdapter adapt;
if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "")
{
cmd = new SqlCommand("insert into [dbo].[user] (Id, username, password) values (#id, #name, #state)", con);
con.Open();
cmd.Parameters.AddWithValue("#id", textBox1.Text);
cmd.Parameters.AddWithValue("#name", textBox2.Text);
cmd.Parameters.AddWithValue("#state", textBox3.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
}
else
{
MessageBox.Show("Please Provide Details!");
}
The database file name is
\WindowsFormsApplication1\WindowsFormsApplication1\Database1.mdf
If you created the database on an actual instance of SQL Server (this can be a local instance on your machine), it appears as though your connection string's data source isn't quite right.
Data Source=DESKTOP-XXXXXXX/Shenal Burkey
There are two problems with this, first the slash (/) should actually be a backslash (). Second, after the slash you have 'Shenal Burkey' with a space. SQL Server instance names cannot contain space characters. That being said, if you installed SQL Server as a named instance, you need to specify the named instance in that place, if you accepted the default instance name it should be 'MSSQLSERVER'. If you are using the default instance name, you can either specify your connection string like this:
Data Source=DESKTOP-XXXXXXX\MSSQLSERVER
or you can omit the instance name entirely and just use:
Data Source=DESKTOP-XXXXXXX
Also, just a tip, you will notice I replaced the specifics of your DESKTOP's hostname with X's, personally I'd recommend editing your question and doing the same. It may not seem like it would be useful, but someone might just pick that up and find a crafty way to do some damage. Better safe than sorry.

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

how to update table data in sql database

I am using asp.net for my project , and I am using the following code , but its not working correctly
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=E:\\WEB_PROJECT\\App_Data\\ASPNETDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "UPDATE info SET fname = #fn, lname = #fl, phone= #ph, recoveryq=#rq, recoverya=#ra WHERE username = #un";
cmd.Parameters.AddWithValue("fn", TextBox3.Text);
cmd.Parameters.AddWithValue("fl", TextBox4.Text);
cmd.Parameters.AddWithValue("ph", TextBox5.Text);
cmd.Parameters.AddWithValue("rq",TextBox6.Text);
cmd.Parameters.AddWithValue("ra",TextBox2.Text);
cmd.Parameters.AddWithValue("un",line);
cmd.ExecuteNonQuery();
con.Close();
Advice plzz i m confused !!! :(
As I've said before on this site - the whole User Instance and AttachDbFileName= approach is flawed - at best! Visual Studio will be copying around the .mdf file and most likely, your UPDATE 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 con.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. ASPNETDB)
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=ASPNETDB;Integrated Security=True
and everything else is exactly the same as before...
cmd.Parameters.AddWithValue("#fn", TextBox3.Text);
You have to specify the parameter name along with '#' .

Why doesn't it work (SQL command in C#?

I'd like to ask you why doesn't this code work? It goes without any error, even cmd.ExecuteNonQuery(); returns 1 (is it if changes one row in the database), but in the actual database, there's absolutely no change. With other database tables, this code works properly, but I'm also not able to remove a row from this table - it behaves asi it if was "read-only", but I have no idea why - yesterday, everything worked fine and now, it's suddenly stopped working :-(
string sConnectionString;
sConnectionString = "Data Source=.\\SQLEXPRESS; AttachDbFilename=\"" + zdielaneInfo.Adresar + "\\rozvrh.mdf\";";
sConnectionString += "Integrated Security=True;User Instance=True";
SqlConnection objConn
= new SqlConnection(sConnectionString);
objConn.Open();
SqlCommand cmd = new SqlCommand("", objConn);
if (zdielaneInfo.Edit)
cmd.CommandText = "UPDATE subject " +
"SET name = #name, day = #day, timeStart = #timeStart, timeEnd = #timeEnd "
+ "WHERE id = #id";
else
cmd.CommandText = "INSERT INTO subject (name, day, timeStart, timeEnd) " +
"Values (#name, #day, #timeStart, #timeEnd)";
cmd.Parameters.Add(new SqlParameter("#name", txbName.Text));
cmd.Parameters.Add(new SqlParameter("#day", dniNaInt(cbDen.Text)));
cmd.Parameters.Add(new SqlParameter("#timeStart", DateTime.Parse(txbStart.Text)));
cmd.Parameters.Add(new SqlParameter("#timeEnd", DateTime.Parse(txbEnd.Text)));
cmd.Parameters.Add(new SqlParameter("#id", zdielaneInfo.Id));
cmd.ExecuteNonQuery();
objConn.Close();
Your problem looks like mdf file overwrite problem.
You are accessing mdf files that are put in the debug folder and replaced every time you run the application.
Be sure that in your project, if you have the database attached within your solution that you are not overwriting it. So select the mdf file in your solution explorer and make sure that its "Copy to output" is set to "Do not copy", then manually copy over the mdf file to the project\bin\debug folder then run the application.
Hope it helps.
Maybe the table is locked.
From HERE, try this:
select
object_name(P.object_id) as TableName,
resource_type, resource_description
from
sys.dm_tran_locks L
join sys.partitions P on L.resource_associated_entity_id = p.hobt_id
If your table is in the result set you have your answer.
Another possibility is the user that you are using to run. Maybe he got privileges revoked.
STOP using the user instance / attachdbfilename options (user instance is deprecated!). Create your database on a real SQL Server, then connect to it directly with your connection string. Using this deprecated feature means that every time you start up your program you're starting with a new copy of the database, and what you inserted yesterday is no longer there - and if you connect to the database using that connection string from two different applications, one is not going to see the data that the other one is changing.

Categories