I retrieve data from database like this:
OleDbDataAdapter dataAdapter
= new OleDbDataAdapter("SELECT * "
+ " FROM myTab1, myTab2"
+ " WHERE myTab1.col1 = myTab2.col3"
, connection);//OleDbConnection connection = new OleDbConnection();
DataTable dataTable = new DataTable("myDataTable");
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
dataAdapter.Fill(dataTable);
Then I use bindingSource in order to access the data in my program, everything works perfect. But after all changes I've made in bindingSource, I need so save them into the database. How can I do this?
Well normally you'd call Update() on the DataAdapter:
dataAdapter.Update(dataTable);
But since your query "joins" two tables it may not be so easy. It may be possible if you turn your SELECT query into a proper join:
"SELECT * "
+ "FROM myTab1 "
+ "JOIN myTab2 ON myTab1.col1 = myTab2.col3"
Some other alternatives:
Write an UPDATE statement that will put the right values in the right tables and set your dataAdapter's UpdateStatement
Populate the dataset with separate tables (one per base table) and join in your app
More info from MSDN:
http://msdn.microsoft.com/en-us/library/xzb1zw3x(v=vs.80).aspx
Related
I'm writing a program using MySQL and WinForm. In my program there's an option to select a VAT Number from a combobox that is retrieve from a table in database. After selecting a VAT Number user have to enter 2 different values into 2 different textbox. After entering those values, the sql query will execute. And show the result in another textbox.
Application form
My sql queries are working fine.
using(MySqlConnection con = new MySqlConnection(cs))
{
con.Open();
//string command;
string command = #"SELECT * FROM `db_liq_blnd_calc_sys`.`tbl_vat_12_spirit_sa` WHERE DIP = '" + txt_Calc_BULK_DIP.Text + "' AND SLIDE = '" + txt_Calc_BULK_SLIDE.Text + "'";
MySqlDataAdapter da = new MySqlDataAdapter(command, con);
DataTable dtable = new DataTable();
DataSet ds = new DataSet();
da.Fill(ds);
DataRow[] returnrow = ds.Tables[0].Select("DIP = '" + txt_Calc_BULK_DIP.Text + "' AND SLIDE = '" + txt_Calc_BULK_SLIDE.Text + "'");
int result = returnrow.Length;
DataRow dr = returnrow[0];
txt_Calc_BULK_BULK.Text = (dr["BULK"].ToString());
con.Close();
}
What I wanna do is, there are 15 table in my database that has same table structure but different data in it. I want to change the sql query that execute by selecting different VAT Number from the combobox.
Since all tables have the same structure, I recommend making one big table for them all and add a VAT Number column to it. Then, to set the values in your combobox, select distinct VAT Numbers from this table. Finally, add the a VAT Number condition to your query.
On a side note, use "Parameterized Query" instead of concatenating values to your query, this would help against SQL Injection Attacks.
I'm new to programming. I have a form (named personal_Info) that fills some person's personal data and saves it in the database table Personal_Information.
2nd I have another form that searches from Personal_Information and shows results in a grid view.
I now want: When search result show in data grid view and when I double click on any row of the shown results I want (personal_info) to open and make an edit at that form and save it.
Please help me.
here is little code which gets data from sql to grid
SqlConnection strconn = new SqlConnection("server=AAG-PC; Database=humanResource; Integrated Security=sspi");
strconn.Open();
SqlCommand strcmd = new SqlCommand("select * from Personal_Information where "
+ searchComboBx.SelectedItem
+ " like '%" + txtBxKeyword.Text.Trim() + "%'", strconn);
SqlDataAdapter ad = new SqlDataAdapter(strcmd);
DataSet ds = new DataSet ();
ad.Fill(ds);
strconn.Close();
gridViewSearchResult.DataSource = ds.Tables[0];
You can use dataadapter to update your changes. It will be something like
changes = ds.GetChanges();
if (changes != null)
{
adapter.Update(changes);
}
you can see more info here
My sqlite code for linking db table to datagrid is:
sqlitecon.Open();
string Query2 = "Select * from Security_details ";
SQLiteCommand createCommand2 = new SQLiteCommand(Query2, sqlitecon); createCommand2.ExecuteNonQuery();
SQLiteDataAdapter dataAdp2 = new SQLiteDataAdapter(createCommand2);
DataTable dt2 = new DataTable("Security_details");
dataAdp.Fill(dt2);
datagrid_security.ItemsSource = dt2.DefaultView;
dataAdp2.Update(dt2);
sqlitecon.Close();
This code links db table to datagrid during form load event.
I want user to be able to:
add new rows on datagrid get inserted into db
edit existing rows on datagrid get updated into db.
Here in following query are my database fields
SQLiteCommand comm = new SQLiteCommand("update Security_details " +
"set id=#id,Code=#Code,Description=#Description,Rate=#Rate," +
"Qty=#Qty,Amount=#Amount,Remarks=#Remarks where id=#id", sqlitecon);
Please tell me the set of commands for inserting and editing db table through datagrid ?Thanks
Move the declaration of the SQLiteDataAdapter to the global class level and declare also a SQLiteCommandBuilder there. Then, before binding your data to the grid, initialize the SQLiteCommandBuilder that will create the UPDATE/INSERT/DELETE commands appropriate for your table automatically (provided that the SELECT returns the primary key of the table)
At this point, when you are ready to submit your data to the database, call the Update method of the global SQLiteDataAdapter instance
public class YourClass
{
SQLiteDataAdapter dataAdp2;
SQLiteCommandBuilder cmdBuilder;
.....
public void BindMyGrid()
{
sqlitecon.Open();
string Query2 = "Select * from Security_details ";
SQLiteCommand createCommand2 = new SQLiteCommand(Query2, sqlitecon);
dataAdp2 = new SQLiteDataAdapter(createCommand2);
cmdBuilder = new SQLiteCommandBuilder(dataAdp2);
DataTable dt2 = new DataTable("Security_details");
dataAdp2.Fill(dt2);
datagrid_security.ItemsSource = dt2.DefaultView;
sqlitecon.Close();
}
....
public void SubmitData()
{
dataAdp2.Update((datagrid_security.ItemsSource As DataView).Table);
}
......
}
If you need a more in depth discussion of this process you could read this MSDN article, it is rather old, regards SQL Server and it is in VB.NET, but the base concept is the same.
In datagrid using C# while updating the sqlite from the form application I am getting index out of range exception .
Cannot find table 0
Below is my code
SQLiteConnection connection4 = new SQLiteConnection
(#"Data Source = C:\APTRABuilder.sqlite;Version =3");
connection4.Open();
string sql2 = "Update table set language1= '"
+ textBoxUpdate1.Text + "' where language2 = '"
+ textBox_Search.Text + "'";
SQLiteDataAdapter connect4 = new SQLiteDataAdapter(sql2, connection4);
DataSet ds4 = new DataSet();
connect4.Fill(ds4);
dataGridView.DataSource = ds4.Tables[0];
Error I am getting in dataGridView.DataSource = ds4.Tables[0];
There are no tables in the DataSet becasue the SQL is doing an UPDATE, not a SELECT, so there are no results to return.
You need to look at creating an UPDATE command for your Data Adapter.
You will also need to learn about adding values with Parameters.
Rather than trying to Fill the DataAdapter you are required to UPDATE the DataAdapter in this scenario. When you Fill a DataAdapter, you are populating the Adapter. To do this you use a SELECT command. These two methods are entirely different.
This Guide below will get you started in understanding Data Adapters better :-
http://msdn.microsoft.com/en-us/library/33y2221y.aspx
Good Luck.
I have a program written in c# visual studio 2008 with SQL server 2005 (.mdf) database.
Here is part of the code:
...
SqlCommandBuilder cb;
cb = new SqlCommandBuilder(dataAdapter);
String[] dataList =new String [8];
...
DataTable resultTable = new DataTable();
FillDataList(data);
dataAdapter = new SqlDataAdapter("insert into ProcessData values('" + dataList[0] + "','" + dataList[1] + "','" + dataList[2] + "','" + dataList[3] + "','" + dataList[4] + "','" + dataList[5] + "','" + dataList[6] + "','" + dataList[7]+"')", con);
dataAdapter.Fill(resultTable);
...
My questions are:
1) Where is the data I added in those lines stored?
2) Why is it that when I Right-Click with the mouse in the Server Explorer->Data Connections->Tables->ProcessData (my table's name)->"show Table Data", I don't see the data but just NULL in the columns, and how can i see the data there?
3) Why when I present this data in a DataGridView sometimes it shows the data and sometimes it doesn't?
Many Thanks!
Without seeing more info on the datalist object and its construction, it's impossible to say. However, you're using the Fill and SQLDataAdapter incorrectly. The FILL relies on the SQLDataAdapter having a SelectCommand property set, which is what your code is bunging the INSERT statement into (that's what the SQLDataAdapter's constructor does). So...your Fill returns nothing as there's no SELECT where there should be.
Your INSERT should be part of the dataadapter's InsertCommand, and you'll need to write a separate SELECT statement to get anything into your resultTable.
I think you need to read some basic documentation on ADO.NET before you write any more code. You're passing an INSERT statement to the SqlDataAdapter constructor, which takes a SELECT statement. You're using the Fill method of SqlDataAdapter where you should be using the Update method. You're building a SQL string with hard-coded values in it where you should be using SqlParameters with references to the DataTable Columns. And is the fact that your DataTable is called "data" but that SQL string is using indexed properties from "dataList" just a typo? Because if it is, DataTable doesn't have an indexed property.
Try doing it like this (you need to fill in the correct connection string though):
// Get the db connection
SqlConnection dbCon = new SqlConnection("connection string");
// Select the data from the database table into a DataSet (even if it's empty)
DataSet myData = new DataSet();
SqlDataAdapter dbAdapter = new SqlDataAdapter("select * from ProcessData", dbCon);
dbAdapter.Fill(myData);
myData.Tables[0].TableName = "ProcessData"; // Keeps the table name consistent for the DataMember property
// Use the command builder to add insert, delete, update commands to your adapter
// You must have a primary key on the table for these to work, though
SqlCommandBuilder dbComBuilder = new SqlCommandBuilder(dbAdapter);
dbAdapter.InsertCommand = dbComBuilder.GetInsertCommand();
dbAdapter.DeleteCommand = dbComBuilder.GetDeleteCommand();
dbAdapter.UpdateCommand = dbComBuilder.GetUpdateCommand();
// Bind the data set to the GridView for viewing / editing
yourGridControl.AutoGenerateColumns = true; // Optional, if you haven't manually added the columns
yourGridControl.DataSource = myData;
yourGridControl.DataMember = "ProcessData";
// Use the db adapter to update the database (by calling those commands) with
// changes made to the DataSet through the grid. This would go in a different
// form event, like a Save Button click.
dbAdapter.Update();
If you don't have a primary key in the ProcessData table, you can directly insert values using this command:
// Insert the data directly with a command
SqlCommand dbInsCommand = new SqlCommand("insert into ProcessData values (" + val1 + "," + val2 + ")", dbCon);
dbInsCommand.ExecuteNonQuery();