How to edit/delete access database record in c# - c#

So i have a problem updating record in my database. My code runs without error, but the record is not updated. Here is the code:
private void button3_Click(object sender, EventArgs e)
{
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
string sql = string.Format("update Alternatif set No ='" + textBox1.Text + "',Kecamatan='" + textBox2.Text + "',Kelurahan='" + textBox3.Text + "',Nama='" + textBox4.Text + "'where No ='" + textBox1.Text + "'");
OleDbCommand perintah = new OleDbCommand(sql, con);
perintah.ExecuteNonQuery();
MessageBox.Show("Data edited successfully");
perintah.Dispose();
con.Close();
}
catch (Exception)
{
MessageBox.Show("Data failed to edit");
}
}

I'm assuming you have proven that the query works to update the record in access - you should consider capturing the int that is returned from ExecuteNonQuery and if it is 0, no records were updated
You should also consider having a good read of http://bobby-tables.com and promise yourself never to write an SQL again like you have there. It is prone to sql injection attack and is a massive security issue
Access is a file based database and typically when added to a visual studio there is a dev version of the file (the file as it was when selected for addition to the project) that is copied to the build directory every time a build is run. The app typically updates the build copy in the bin directory, not the dev copy outside the bin directory.
Developers then go looking in the dev copy and are surprised that no change was made- they're looking in the wrong file.
Or they go looking in the build copy, but after another build has been run and the edited db has been overwritten with a fresh, empty copy of the dev db. Search your project folder for all db and ensure you're inspecting the right one
You can stop the build process replacing the bin folder version of the file every time by finding the db in the solution explorer, getting properties on it and setting the Copy To Output Directory to something other than Copy Always. I personally use Copy If Newer

Related

Insert query is run successfully, but the data is not inserted into the database (C#)

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

Dynamic Datasource Path C#

I created an app where a combobox is bound with an Access Database. The application was working fine on my computer because the source path in the connectionstring I defined was related to my computer. I copied the project folder to another computer which gives error of not finding the database at the specified location.
Can I dynamically set the path from a textbox or some other input? Can I call a database from the application where the source path doesn't matter. Even when I refer to Resources.Database1 it still gives full path to application folder for my computer which doesn't work on another computer. Any idea would be appreciated. Thanks!
My code is the following:
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand();
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO SubrubDatabaseT(SuburbName,DeliveryTime) values('" + textBox1.Text + "','" + textBox2.Text + "')";
OleDbConnection connect = new OleDbConnection();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\WoolsValley\Desktop\Database1.accdb ;
Persist Security Info = False; ";
connect.Open();
command.Connection = connect;
command.ExecuteNonQuery();
MessageBox.Show("Data Saved Successfully");
connect.Close();
}
For your case, the solution is to use an App.config (or Web.config depending on the type of the project you are developing) file and put all the settings there. Then if the path doesn't exist, you can still change it to an existing one in this file, and it will not be necessary to recompile the application.
This is the main use of these lind of files, to add there any settings that could change on the users machines or when the application is published and it may need little adjustments, as in this case, and it may not be needed to recompile for every computer the application runs.
As you mentioned yourself, you can simply have a text box for the file path or maybe an OpenFileDialog component to select the file. You then pass that in the connection string:
//GetFileSource() a method that gets the source from somewhere, like a textbox or a configuration entry in app.config.
var fileSource = GetFileSource();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileSource + ";Persist Security Info = False;";
What's equally important is that you make sure the file actually exists at the destination.
You could create a method that searches the users folder for data files or let the user specify a data file on startup and save that to the users profile directory. There are many ways to do this and which way you choose depends on factors like how is the data file copied to the users PC, are there many data files possible, etc.
If the data file only exists with the app, there is only one data file possible, and the data file is copied/created at deployment time (ie. when you run the MSI) then put it in the app.config instead as a connection element. See Connection Strings and Configuration Files.
First thing is to always use parameterized queries. See https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters(v=vs.110).aspx
Remarks
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.
Your code refactored with using statements and parameterized inputs.
// get file from the drop down
var filePath = getSelectedDataFile();
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath))
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO SubrubDatabaseT(SuburbName,DeliveryTime) values(?,?)";
cmd.Parameters.Add(new OleDbParameter("#suburbName", OleDbType.VarChar)).Value = textBox1.Text;
cmd.Parameters.Add(new OleDbParameter("#deliveryTime", OleDbType.VarChar)).Value = textBox2.Text;
con.Open();
cmd.ExecuteNonQuery();
}
Note that:
OleConnection and OleDbCommand are wrapped in using blocks so they are disposed/cleaned up even when an exception occurs.
Parameters are now used instead of hard coding the string values
Parameters use the correct data types

Changes do not get saved permanently into SQL Server Compact edition

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.

Insert values to table in database in c#

I have a Winforms application and database to save data from user.
When I insert data everything works fine but when I clean the solution and load the GUI of the database to see the old data.. I don't see the datam the datagridview is empty.
using (SqlConnection con = new SqlConnection(dataBase.Connection.ConnectionString))
{
using (SqlCommand wow = new SqlCommand("insert into GamesTbl(Type,Date,Time) Values(#type,#date,#time)", con))
{
wow.Parameters.AddWithValue("#type", "vsPC");
wow.Parameters.AddWithValue("#date", DateTime.Now.Date);
wow.Parameters.AddWithValue("#time", DateTime.Now.TimeOfDay);
try
{
con.Open();
wow.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
What is wrong?
EDIT: binding data on DBGui_load
private void DBGui_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = playersTblBindingSource;
playersTblBindingSource.DataSource = DB.GamesTbls;
}
EDIT: my connection string:
"Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated
Security=True;User Instance=True"
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (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. Database1 - or while you're at it - give it a more sensible name...)
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=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
Seems liks you are missing DataBind.
private void DBGui_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = playersTblBindingSource;
dataGridView1.DataBind(); // you are missing this
playersTblBindingSource.DataSource = DB.GamesTbls;
}
As an alternative solution, what you can do to fix the problem is to set the property of your database file in your solution as follows
Copy To Output Directory: do not copy

C# system.io.filenotfoundexception

I am creating an app for my work to track behavior management over the course of a school year. To do this, I obviously needed a database. I built the program so that it would, when opened, check to see if the database exists, and if it doesn't, it creates one, and inputs the schema. This works perfectly on my dev computer, but when I switch it to a computer using windows XP it gives an error saying system.io.filenotfoundexception. I can't figure out why it won't create the database.
I am using Visual C# 2010 Express. And the database is made in sql server ce.
if (!File.Exists("chart.sdf"))//Checks if file is already in existance when app is opened
{
dbCreated = createDb();//If there is no database, creates one
}
public bool createDb()//Creates the database if needed
{
bool success = true;
//Holds sql schema for the table
string[] tableCreateArr ={"create table childNameId"
+ "(childId INT IDENTITY PRIMARY KEY, "
+ "childFName nchar(40), "
+ "childLName nchar(40));",
"create table leaderNameId"
+ "(leaderId INT IDENTITY PRIMARY KEY, "
+ "leaderFName nchar(40), "
+ "leaderLName nchar(40));",
"create table TagPulledId"
+ "(tagId INT IDENTITY PRIMARY KEY, "
+ "childId INT, "
+ "leaderId INT, "
+ "day TINYINT, "
+ "month TINYINT, "
+ "year INT);",
"CREATE TABLE tagInfo"
+ "(tagId INT, "
+ "color nchar(10), "
+ "description ntext)"};
SqlCeEngine dbCreate = new SqlCeEngine(connectString()); // creates the database obj
dbCreate.CreateDatabase(); // creates the database file
SqlCeConnection tempConnect = new SqlCeConnection(connectString());//Connects to the new database
SqlCeCommand objCmd = new SqlCeCommand();//Creates an sql command obj
tempConnect.Open(); // opens the connection
objCmd.Connection = tempConnect; //Connects the command obj
foreach (string strCmd in tableCreateArr)//Iterates throught he sql schema to create the tables
{
try
{
objCmd.CommandText = strCmd; //sets the CommandText to the next schema entry in the array
objCmd.ExecuteNonQuery(); //Executes the create query
}
catch (SqlCeException sqlError)
{
MessageBox.Show(sqlError.Message, "SQL Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
success = false;
}
}
tempConnect.Close();
return success;
}
I can't figure out why the app isn't making the database, it seems to work on some computers, while not working on others. Any help would be great! Thank you.
if (!File.Exists("chart.sdf"))
You seem to want to create the database in the same directory as your program. Yes, that will work on your dev machine but that's not going to work on a regular machine. The typical install directory (c:\program files\etc) does not permit write access to files.
You will need to use Environment.GetFolderPath() to get an ApplicationData directory that you can write to.
It is often a lot easier and less error prone to let an installer create the appdata directory and copy the initial .sdf file in there. Albeit that Setup projects are not supported by the Express edition. There does come a point where hacking code to work around the Express edition's restrictions is defeating the price of the product license. You're pretty close here.
Make sure you have deployed all the dll Sql Server Compacts need. I'm not sure you get them when you install .NET framework. The dll needed are :
sqlceca35.dll
sqlcecompact35.dll
sqlceer35EN.dll
sqlceme35.dll
sqlceoledb35.dll
sqlceqp35.dll
sqlcese35.dll
You can find more details on this MSDN page about Sql Compact Deployment for various versions of the database engine.

Categories

Resources