I have a problem,
private void button_Submit_Click(object sender, EventArgs e)
{
try
{
string connectionString = #"Data Source=Database_TouchPOS.sdf;Persist Security Info=False;";
using (SqlCeConnection connection = new SqlCeConnection(connectionString))
{
using (SqlCeCommand command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "INSERT INTO Product (Title,Price,Category_Id) VALUES (#title, #price,#category_Id)";
command.Parameters.AddWithValue("#title", textBox_Title.Text);
command.Parameters.AddWithValue("#price", textBox_Price.Text);
command.Parameters.AddWithValue("#category_Id", comboBox_Category.SelectedIndex);
command.ExecuteNonQuery();
MessageBox.Show("Product Added Successfully...");
}
connection.Close();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Everything seem to be fine, but still can't add data into database.
I did try with complete database path, example c:\project\database.sdf
I did a lot of search before asking. I saw similar problems but not even a single one works for me.
Data are added when compiling but not committed to database. I can see the data after second attempt of debugging.
Please kindly try to explain in detail.
Thanks
You are probably facing this, http://erikej.blogspot.com/2010/05/faq-why-does-my-changes-not-get-saved.html suggest you use a full path to your database file in your connection string.
Did you try to use transactions explicitly?
IDbTransaction transaction = connection.BeginTransaction();
//add to database
transaction.Commit(); // before close connection
This is a very old thread, so I don't know if it will help anyone if I put my answer.
I had this problem, too.
When I executed an update or insert code in C#, apparently, everything was ok, but when I looked up the database, there was no change.
The thing was that while debugging I had the database opened in a Management Studio. And somehow this obstructed the database changes even when there was no error message.
Closing the Management Studio and opening it after executing the code, the changes where perfectly stored in the data base.
Regards.
complete example for those seeking like me... #"Data Source=C:\Users\MYPC\Documents\Visual Studio 2010\Projects\MyProjectFolder\MyProject-1\bin\Debug\MyDatabase.sdf;Persist Security Info=False;";
thank for this example. This saved my day.
Related
I need to insert data when user clicks. But, my code isn't doing it. Even though it displays the data inserted message, the data is not inserted. How can I find the mistake?
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=**F:\Blackhat\Blackhat\Blackhat.mdf**;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert Into Clients(name) VALUES ('"+clientname.Text+"')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Success "+clientname.Text);
con.Close();
}
catch (SqlException ex)
{
MessageBox.Show("Failed"+ex);
}
}
Since there are no exception, the issue would be like, you are writing it to a wrong file in a wrong location or something of that sort.
If it fails to write, there will be an exception and it goes to the catch block.
So we can expect that there are nothing wrong in the c# code.
If you are checking the entries using SQL server management studio, you need try querying the database. The edit 200 rows option needs a database refresh and edit again after closing the existing edit tab. else the vales do not appear to be changing.
Hope this helps. If the issue is something else, please mention in the comments.
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
So this is probably the most naive question but that is what questions are for I guess;
Then, my issue is that I have no idea on how to connect Visual C# Express 2010 to Access 2007 and do the typical insert, update, delete, search in an application in C#, I have just learned the basics (finished a console tutorial, which I believe is more than enought, having previous background of VB6 using access 97), and I have been searching here and in the web, but the only thing I could find where the msdn tutorials which I dind't find really clear.
So in my app I just need to link comboboxes, query those values to obtain new ones, do calculations and then store in arrays (and maybe show these in datagrids as well as edit them from said datagrids, which is a bit more complicated I guess) and finally store them in various tables, but I haven't really found a strong (or most likely simple) manual that will guide me to create the typical app insert, update, delete using winforms.
Do you guys have any good links in order to do this?
Thanks.
You can try with this code
Here link about string connection : http://www.connectionstrings.com/access-2007
var query = "...";
var connectionString = "...";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
using(var command = new OleDbCommand(query))
{
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}
Right, I have been tasked with developing a new application in MVC3 that unfortunately has to integrate very slightly with a classic asp web site. This won't be forever as the old site will get an update at some point, but not yet. In the mean time however the new MVC3 application will need a little bit of access to the database for the old site, which is a old MS Access .mdb whereas the new app will be using sql server 2008.
I would greatly appreciate it if someone could give me some examples of how to connect to the access db, aswell as how to execute sql queries (i am fine writing the sql, just got no idea how to execute against the database from my mvc3 app).
thanks in advance
EDIT: I've not got much experience with the old site, but it appears to use the JET adaptor if that helps! ;-)
Your question requires an answer too extensive to be given in detail
I will give you a check list of things and class to research
Define the connection string used to reach your database [see
here]
Create and open the OleDbConnection
Define your OleDbCommand and the command text to be executed
Create and use an OleDbDataReader to read your data line by line
Create and use an OleDbDataAdapter to read your data and load a
DataSet or DataTable
Now don't forget to close your connection and use parametrized query
string connectionString = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
public void InsertRow(string connectionString, string insertSQL)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OleDbCommand command = new OleDbCommand(insertSQL);
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}
I have a SQL Server database in a C# project.
I use a connection string to connect to it.. I can use the method ExecuteNonQuery to insert data, no problem there.
But when I delete, it only deletes it momentarily, as soon as I restart the application it kind of rolls back the deletion.. Any ideas?
PS: I tested the string in a direct query, and it worked fine there.
public void executeNonQuery(string input)
{
db.Open();
SqlCommand cmd = new SqlCommand(input, db);
cmd.ExecuteNonQuery();
db.Close();
}
EDIT: DELETION CODE:
private void buttonSletPost_Click(object sender, EventArgs e)
{
if(dataGridView1.GetCellCount(DataGridViewElementStates.Selected)>0){
for (int i = 0;i < dataGridView1.GetCellCount(DataGridViewElementStates.Selected); i++)
{
String str1 = String.Format("WARNING about to DELETE:\n {0} \n BE CAREFULL NO TURNING BACK NOW!", Regnskab.getInstance().dbSelectPostID(dataGridView1.SelectedCells[i].Value.ToString())[0].ToString());
if (MessageBox.Show(str1, "Confirm Deletion", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string str = String.Format("DELETE FROM PostTable WHERE PostID={0}", dataGridView1.SelectedCells[i].Value.ToString());
Database.getInstance().executeNonQuery(str);
Console.WriteLine(str);
}
}
}else {MessageBox.Show("No cells selected");}
}
Which will give following output:
DELETE FROM PostTable WHERE PostID=7
Connection string in app.config:
<connectionStrings>
<add name="EndProject.Properties.Settings.DBtestConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DBtest.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" providerName="System.Data.SqlClient" />
private Database()
{
string connStr = ConfigurationManager.ConnectionStrings["EndProject.Properties.Settings.DBtestConnectionString"].ConnectionString;
db = new SqlConnection(connStr);
}
And then I open and close it, so the connection ain't open each time.
To be honest:
I don't exactly know where to see my DB info, here's some info from properties in VS2010.
Provider: .NET Framework Data Provider for SQL Server
Type: Microsoft SQL Server
Andrew's 3rd: I think they are deleted momentarily because I reloaded the information in my datagridview and from there it is gone. But then when I close the application and start it again, it is back...
Also i just checked with VS2010's server explorer and did a "Show Data" after I deleted (before I shut it down) and it wasn't deleted.
But I'm totally clueless now. :-(
Many applications use Transactions to manage db connections. SQL Server doesn't do it by default, but other factors in your application may be doing this.
Also, if you're really doing this, and your input is coming from a user interface, I can't wait to introduce you to Little Bobby Tables
Use the SQL Server Profiler to run a trace and capture the actual T-SQL statements that are getting executed on the database.
This is the easiest solution.
The behavior you're describing sounds like autocommit is off. Try the following and see if the record(s) stays deleted:
public void executeNonQuery(string input)
{
db.Open();
using (var txn = db.BeginTransaction())
{
SqlCommand cmd = new SqlCommand(input, db);
cmd.Transaction = txn;
cmd.ExecuteNonQuery();
db.Close();
txn.Commit();
}
}
Ok it was apperently me who was mistaken on the inserting part...
Someone suggested that i was because of the Visual Studio databases created every time the applikation ran.
So i installed MS SQL 2008 R2. Created a new DB with same layout.
Changed the connection string
And wuupti woo it seems to work, ill come back to this thread if it breaks down later..
But delete + insert both working greatly now :-)
Thanks to all who tried to help!