Update database using SqlCeDataAdaptor - c#

I populate a listview from a Dataset that accesses sqlserver in visual studio 2008 express edition. I've been trying to update the listview and database simultaneously.
SettingTxt.Text references a textbox
With the following code, I've been able to update the list view with the information entered into the textbox, but the same update is not performed in the database. If anyone can help me resolve this, I would greatly appreciate it. I know there are alot of forums online regarding this exact problem, but I can't seem to get it working.
thisConnection = new SqlCeConnection("Data Source=AugMedDB.sdf;Password=");
thisConnection.Open();
SqlCeCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = "UPDATE Patient SET Setting = \'" + SettingTxt.Text + "\' WHERE (PtID=0) AND (EquipID=1) AND (Control='Lever')" ;
SqlCeDataAdapter adp = new SqlCeDataAdapter();
adp.UpdateCommand = cmd;
dataSet.Tables[0].Rows[0][2] = SettingTxt.Text;
adp.Update(dataSet);
Thanks in advance.
Moved from an answer:
What I currently have is:
SqlCeCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = "SELECT column FROM table WHERE id=0";
SqlCeDataAdapter adp = new SqlCeDataAdapter(cmd);
adp.SelectCommand = cmd;
DataSet ds = new DataSet();
ds = dataS.getDataSet();
adp.Fill(ds, "Patient");
SqlCeCommand comm = thisConnection.CreateCommand();
comm.CommandText = "UPDATE table SET Setting = 'value' WHERE (PtID=0)";
adp.UpdateCommand = comm;
adp.Update(ds, "Patient");
And I'm not understanding all the tutorials I find. Thanks in advance.
Update:
Yet even something as simple as the following doesn't update the database:
SqlCeConnection thisConn = new SqlCeConnection("Data Source=AugMedDB.sdf;Password=");
String query = "UPDATE Patient SET Setting = 'TopyTruck' WHERE (PtID=0) AND (EquipID=1) AND (Control='Lever')";
thisConn.Open();
SqlCeCommand commd = new SqlCeCommand(query, thisConn);
commd.ExecuteNonQuery();
thisConn.Close();

Your UPDATE statement is not suitable for an Adapter.Update(), for that it needs parameters and must be aligned with the SELECT statement.
You could try to execute that Command directly (w/o the adapter) or create a better update statement (using the dataset designer ).
Update
After filling the dataset,
generate the other SQL statements with a CommandBuilder (I think it exists for SqlCe)
or use your use your own Update command without the adapter. Just call comm.ExecuteNonQuery()
Tip 1: It may help to create a temporary (WinForms) project and use the VS tools to "Add a Datasource". You can look in the Dataset designer how VS generates the commands etc.
Tip 2: There are other options available, like entity framework. Datasets are (becoming) an "end of life" tech.

Thank you so much for all your help. I actually found the source of the problem. I had multiple references to the database; one within my project and another copy in bin/debug. I was correctly updating the copy in bin/debug but I was looking at the copy in my project. Once I deleted all copies, other than the one in bin/debug, it all worked and made sense. Now I see the updates in the database in bin/debug/

Related

Create dinamically a Dataset to fill reports on Visual Studio

I am searching for a way to create dinamic Datasets to be binded to my reports
(I am using C# on Visual Studio 2015 Community).
Can anyone explain how can I do it?
The first idea is to create a Dataset from a query then bind it to my report,
but I cannot create a report without telling VS a DataSet (which must be connected to a DB using a static ConnectionString (VS purposes me only the Wizard, I have no idea on how to do it dinamically)
Example Code of what I would like to have:
DataSet myReportDS = ADO.getDS("SELECT * FROM" +
"Table1 JOIN Table2 ON Table1.pkey = Table2.fkey");
//here I am stuck because I don't know even how to add objects without a
//static connection to my report (Designer) and how to bind it.
Have also in mind that the DBMS is PostgreSQL.
Thanks a lot.
In the end I found this article to solve my problem
https://blogs.msdn.microsoft.com/magreer/2008/10/16/setting-the-datasource-for-a-report-at-runtime/
The problem in fact is that VS forces the user to have a static DataSet to permit the report creation. So basically I had to create a copy of my DB Schema in local environment, then I executed my queries normally and then used Report.Fill() method. As soon as the schema is the same it works!
You could use a SqlDataAdapter or OleDbDataAdapter.
For example:
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet customers = new DataSet();
adapter.Fill(customers, "Customers");
There are more examples on the msdn site.
Source: https://msdn.microsoft.com/en-us/library/bh8kx08z(v=vs.110).aspx

Unable to display record on Crystal Report in c# window application

Yesterday i created a stored procedure with the help of you people in which i use select command to retrieve data from database then perform calculations ,this procedure works fine when it run in SQL Management Studio and display record as i want.
My Stored procedure is working fine.
and record which i retrieved in MS SQL Management studio is looking as:
Now i need to show this records on crystal report and did this as:
cmd = new SqlCommand("sp_Rpt_Emps_Attnd", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#strt", Convert.ToDateTime(dtStart.Text).Date);
cmd.Parameters.AddWithValue("#end", Convert.ToDateTime(dtEnd.Text).Date);
conn.Open();
int qry = cmd.ExecuteNonQuery();
SqlDataAdapter sdt = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
sdt.Fill(ds);
Rpt_Emps_Attend crp = new Rpt_Emps_Attend();
crp.SetDataSource(ds);
crp.SetParameterValue("#total_hrs", t_hrs);
crystalReportViewer1.ReportSource = crp;
crystalReportViewer1.Refresh();
conn.Close();
But in crystal report i am unable to see these record and my report display some record as:
Please, Any body suggest where am i missing something or am i wrong any where?
thanks for your precious time and kind reply.

how to talk to local databases?

I just added a new "local database" in my project using visual studio. Now I added the "New Data Source".
What I want to know is how you can do sql queries to the DB. I know how this is done in PHP but cant find good information about how to do this in C#. All I find is tutorials on how to drag detail or gridviews into the form.
I have one database called 'words' with three tables. I want to be able to do update queries to a row in each of these tables. something like this:
UPDATE easy SET words='blahblahblah' WHERE id=1;
How do you do this?
I am going to use SQL Server as example.
First you need to find out the connection string which should be similar to
_connectionString = "Data Source=(localdb)\\v11.0; Initial Catalog=words;Integrated Security=true;"
and then you do
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE easy SET words='blahblahblah' WHERE id=1;", connection))
{
cmd.ExecuteNonQuery();
}
}

MS Access DB doesnt save changes after execution (C#)

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".

Tutorial on connecting c# to SQL server

I want to be able to edit a table in a SQL server database using c#.
Can someone please show me a very simple tutorial on connecting to the DB and editing data in a table.
Thank you so much.
First step is to create a connection. connection needs a connection string. you can create your connection strings with a SqlConnectionStringBuilder.
SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder();
connBuilder.InitialCatalog = "DatabaseName";
connBuilder.DataSource = "ServerName";
connBuilder.IntegratedSecurity = true;
Then use that connection string to create your connection like so:
SqlConnection conn = new SqlConnection(connBuilder.ToString());
//Use adapter to have all commands in one object and much more functionalities
SqlDataAdapter adapter = new SqlDataAdapter("Select ID, Name, Address from myTable", conn);
adapter.InsertCommand.CommandText = "Insert into myTable (ID, Name, Address) values(1,'TJ', 'Iran')";
adapter.DeleteCommand.CommandText = "Delete From myTable Where (ID = 1)";
adapter.UpdateCommand.CommandText = "Update myTable Set Name = 'Dr TJ' Where (ID = 1)";
//DataSets are like arrays of tables
//fill your data in one of its tables
DataSet ds = new DataSet();
adapter.Fill(ds, "myTable"); //executes Select command and fill the result into tbl variable
//use binding source to bind your controls to the dataset
BindingSource myTableBindingSource = new BindingSource();
myTableBindingSource.DataSource = ds;
Then, so simple you can use AddNew() method in the binding source to Add new record and then save it with update method of your adapter:
adapter.Update(ds, "myTable");
Use this command to delete a record:
myTableBindingSource.RemoveCurrent();
adapter.Update(ds, "myTable");
The best way is to add a DataSet from Project->Add New Item menu and follow the wizard...
Assuming you're using Visual Studio as your IDE you could just use LINQ to SQL. It's a pretty simple way to interact with your database and it should be pretty quick to get going.
Using LINQ to SQL is a pretty simple walk through in getting it up and running.
Have a read of the MSDN tutorial on Creating Data Applications. You may be able to clarify your question, or find the answers you need.
There is info on editing the data in the app but you have to get connected and load it into your app first.
The only reason to do this in C# is if you want to automate it somehow or create an interface for non-technical users to interact with the database. You can use a GridView control with an SQL datasource to manipulate the data.
#kevin: if he's just learning, I think its probably simpler to have him use SQLCommand object (or SQLDataAdapter).

Categories

Resources