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 '#' .
Related
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.
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());
}
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?
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();
}
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();