I have .mdb database, and code like this:
using (OleDbConnection connection = new OleDbConnection(myConnectionString))
{
using (OleDbCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "UPDATE myTab SET col2 = #val1 WHERE col1 = #val2";
cmd.Parameters.AddWithValue("#val1", 0);
cmd.Parameters.AddWithValue("#val2", -1);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
I get data from db, change it in my gui programm, then save it in db. Changes saves, but not in db (I don't know where), so when I run program, change data, close program, then again run - changes remain, but when I open db (not in programm), there are no changes saved, and again run - all changes disappear.
PS: when I commit changes, then run program several times, all changes disappear too, after (3-4 runs)
When we we add .mdb in project root in VS ,when change structure ,VS default delete .mdb file in debug folder and replace new file; now you can change this defult :
1- right click .mdb file and select option
2- set Copy To Output Directory to Do Not Copy
It is most likely the WHERE clause of your update statement isn't locating any records to update.
http://weblogs.asp.net/stevewellens/archive/2009/10/16/why-sql-updates-fail-three-reasons.aspx
Related
I want to give the users to the ability to update their info on database. I made the button to for the software to take the name from one of the textboxes and send it to the database.
public void Updatebtn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Ray-a\\Downloads\\New folder (2)\\Blood Donation\\Blood Donation\\App_Data\\BloodDonationDB.mdf\";Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("Update Users set First_Name=#fn WHERE ID = '2' ", con);
cmd.Parameters.AddWithValue("#fn", UFirstName.Text);
cmd.ExecuteNonQuery();
con.Close();
}
I watched a YouTube video and followed step by step. But it didn't work.
The button works and executes command. But something is wrong with either sql command or connection because the database doesn't get updated
because your codes seems okey to me with no problems in it i'll give you some tips that will make sure you almost avoiding most mistakes biggeners like me did which caused unexplaind errors.
these tips will REALLY REALLY help you in your programming journey.
when adding a new local database, create a newfolder and name it DataBaseFolder as an example inside your project folder , so you always know where is your database and you dont get confused about other databases in the default location VS saves them, and its better that the project folder is placed in the partition "C" in a default folder of windows.
when creating a new table, name it probably in the definition part at the bottom where you can see:
create table [dbo].[TableName] then press Ctrl + s, make sure to save that table in the same folder as your database, so you always know this table is for this project.
)))) each time you update your table definition like column name or type, or adding a new column or deleting an existing one, make sure to press Ctrl +s and save the table (replace) in the same folder you originally created it, that will make sure you don't get the error most new developers like me were stuck at which is the update window is taking forever to preview the changes.
))))) to make it easy for myself to use the sql commands, i created a script (class.cs) and put the important codes in methods with parameters so i save a lot of time when i was restarting over my program because of some mistakes i did :D
first i defined my sql connection in the class named SqlCodes:
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Ray-a\\Downloads\\New folder (2)\\Blood Donation\\Blood Donation\\App_Data\\BloodDonationDB.mdf\";Integrated Security=True");
then i created my methods, examples:
public void QueryCommand(string QueryString)
{
con.Open();
SqlCommand cmd = new SqlCommand(QueryString, con);
cmd.ExecuteNonQuery();
con.Close();
}
public void FillingDataGridView(parameter1,parameter2, parameter3)
{
con.Open();
some code;
con.Close();
}
So, back to my main class where my button will function:
SqlCodes sqlCodes = new SqlCodes();
in the button i now can write:
sqlCodes.QueryCommand("insert into MyTable values (your values)");
or
sqlCodes.RefreshDataGridViewAfterEntry (parameter1,parameter2,parameter3)
or
string queryCommand = " insert into MyTable values (your values)";
sqlCodes.QueryCommand(queryCommand);
or in the load form method so when you open the program it shows the data you want instantly
{
sqlCodes.FillingDataGridview(parameter1,parameter2,parameter3)
}
if you're having errors with your database, don't delete the files you will find in the solution explorer because it will cause you some errors i couldn't figure their solution, just delete the database in the server explorer, and don't forget to change the sql connection path in the SqlCodes Class you created.
that will save you time and and to avoid errors and make your code very simple, instead of copy paste/ writing about 7 or 8 lines each time you want to do something with your database.
I managed to solve the problem.
As it Turns out. clicking the button also calls page_load. Which has a code that replaces text in the textbox. So the button would first call page_load. Retrieving data from the databox. Then it would put in the textbox.
Then it would take data from the same textbox again and send back it to the database.
I managed to fix it by putting the code in pageload inside in if statement. And then i put !Page.IsPostBack condition inside the if statement.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Active"] != null && Session["Active"].ToString()
=="Yes" && !Page.IsPostBack)
{
GetUserData();
}
}
Hope that helps.
public partial class Form1 : Form
{
OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString);
public Form1()
{
InitializeComponent();
}
private void btn_add_Click(object sender, EventArgs e)
{
OleDbDataAdapter items = new OleDbDataAdapter();
connection.Open();
OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName, SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
command.CommandType = CommandType.Text;
command.ExecuteReader();
connection.Close();
MessageBox.Show("Inserted!");
}
}
Given that it's Ole, I'm guessing this is Access - a file based database. Your insert is running successfully but you don't find the data in the db when you look
You need to appreciate that typically withba probe t that uses an access db you will have several copies of the db but the most relevant ones are probably like:
C:\myprojects\windowsapp1\your.accdb
C:\myprojects\windowsapp1\bin\debug\your.accdb
The first one is the db you see in the solution explorer. The second one is placed next to your debug exe every time you run a build, or possibly every time you click play in VS. The second one is probably the db your program is inserting into
You're either looking in the wrong db for your data, or every time you run your program the build process erases the changes db by copying the empty one (first one) over the top of it.
Run your app, insert your data, don't quit your app, Search your entire project folder for all instances of your db file. Look in all of them. You'll probably find your data
Right click the db file in solution explorer, choose properties, and change the Copy action to Copy If Newer
Now the build process will only erase your db in the debug folder if you make a change to the source db, eg add a table to it etc
I am having a weird problem. I am using vs2012 to connect to SQL Server CE and executing some insert queries.
public void EstablishConnection()
{
connection = new SqlCeConnection("Data Source=DataDump.sdf;Persist Security Info=False;");
try
{
connection.Open();
Console.WriteLine("Connection Successful");
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
public void AddRecord(string link,string content)
{
int num = 0;
var command = new SqlCeCommand("INSERT INTO Webpages(Link,Data) VALUES('"+link+"','"+content+"');",connection);
num = command.ExecuteNonQuery();
Console.WriteLine("Command Successful rows affected"+num);
var cmd2 = new SqlCeCommand("SELECT * FROM Webpages",connection);
SqlCeDataReader reader = cmd2.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0]);
Console.WriteLine(reader[1]);
}
}
However I am having the problem that once VS is closed and when later I open it to display the data, the data is gone as it was never saved
How is that possible when it is clear then it executed the query?
It is a common scenario.
You have your database file listed between your project items.
Its property Copy to Output directory is set to Copy Always.
Now, you run your debug session with VS. The compile is succesfull and VS copies your sdf file from the project folder to the current output directory (BIN\DEBUG).
Your code runs smoothly and inserts the data in your database file (on the output directory).
You stop and restart the debug session to fix something, but, at restart, the VS recopies the empty file from the project folder to the output directory.
To break this circle, set Copy to Output Directory to Copy Never (or Copy if Newer)
EDIT Another source of confusion is due to the use of SERVER EXPLORER to view the contents of your database file. If the server explorer use a connection string that points to the database file in the project folder you never see the changes made to the database file in the Output Directory.
You should create two connections in Server Explorer, one named DEBUG DataDump that points to PROJECTFOLDER\BIN\DEBUG. You could use this connection to check the data inserted during debug or for other debugging tasks. Another one, called DISTRIBUTION DataDump, points to the file in the project folder and you make here your schema changes needed for the distribution of your app.
Said that, keep in mind that your code has a BIG problem. It is called Sql Injection
A parameterized query will avoid quotations problems and remove the Sql Injection
int num = 0;
var command = new SqlCeCommand("INSERT INTO Webpages(Link,Data) " +
"VALUES(#lnk, #cnt)",connection);
command.Parameters.AddWithValue("#lnk", link);
command.Parameters.AddWithValue("#cnt", content);
num = command.ExecuteNonQuery();
set Copy to Output Directory property as Copy if newer for your sdf file
it seems now you have set it as copy always which result :
The database file is copied from the project directory to the bin
directory every time that you build your application. Any changes made
to the data file in the output folder are overwritten the next time
that you run the application.
I create simple example to create question easyer.
So in my c# project I create an mdf database with articles. Then I connect database in my program and read values from table articles. It gives me results, but not the latest.
If I have one result it showes me this one. Then I go in articles table to add one new article and run program again and in this case program showes me only the first one. But if I "Build solution" it finds all of them.
What I have to do? I wish, that program will have the latest result on startup.
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
try
{
cn.Open();
string sqlQuery = "SELECT * FROM Articles";
SqlCommand sqlCommand = new SqlCommand(sqlQuery, cn);
SqlDataReader sqlDataRead = sqlCommand.ExecuteReader();
while (sqlDataRead.Read())
{
MessageBox.Show(Convert.ToString(sqlDataRead["ArticleLabel"]));
}
sqlDataRead.Close();
sqlDataRead.Dispose();
sqlCommand.Cancel();
cn.Close();
}
catch (Exception) { MessageBox.Show("Database error!"); Application.Exit(); }
If your MDF file has the property Copy To Output Directory set to Copy Always, then every time you build your application a fresh copy of the database file is copied from the project directory to the output Directory (BIN\DEBUG or BIN\RELEASE).
Of course this destroy any changes you have made in a previous run of your program
Change the property to Copy if Newer
Also, don't be fooled by what you see in the Server Manager Windows. The connections there could not point to the database in the Output directory but on the database in the Project Directory where you don't write anything.
I have the following code for using an access database
OleDbConnection con = new OleDbConnection(myproject.Properties.Settings.Default.myDBConnectionString);
con.Open();
OleDbCommand command = new OleDbCommand("INSERT INTO components (name) VALUES (#p_col1)", con);
command.Parameters.Add("#p_col1", OleDbType.VarChar).Value = "test row";
int rows = command.ExecuteNonQuery();
At this point rows value is 1 and when I make select queries after that the row inserted is available. The problem comes when the program finishes: in further executions that row isn´t there anymore.
I´ve tried with transactions
OleDbTransaction transaction = con.BeginTransaction();
command.Transaction = transaction;
transaction.Commit();
and using DataSets and ADO this way
//... add row to dataset ...
OleDbDataAdapter sda = new OleDbDataAdapter("select * from components", con);
OleDbCommandBuilder cb = new OleDbCommandBuilder(sda);
sda.Update(ds.Components); //tried with ds.Components.AcceptChanges(); before and after this line
but in every case i have the same problem, seems like the insert query is not done in the real database. Do you know why can this be happening???
Thanks in advance
Is the database in your bin directory? Is it also part of your project? I have seen this happen when every time you build it overwrites the database in your bin directory with the one from the project directory, so it appears things are not getting saved.
There may be more than one database and you are not inserting to the one you think you are inserting to.
MS Visual Studio builds the Access DB into the product.
--- The product is located in your bin directory.
--- To view any and all changes to your DB via application use this one
When you initially add the DB to the project, it is set to always update the product on build.
This can be a good thing, but I find it rather annoying.
In order to fix this:
Select the MS Access DB from your Solution Explorer,
Hit F4 to go to it's properties,
Change the field "Copy to Output Directory" to "Copy if newer" instead of "Always".