I have an access database that I am manipulating with C#.
I have connected to it, retrieved a data-set from it and can add rows to a table. Now I am trying to clear a table and I am unable to get it to work.
I have tried TRUNCATE TABLE table_name but that throws an exception saying that I must use either DELETE, INSERT, PROCEDURE, SELECT or UPDATE and I have tried Delete FROM table_name However that throws an DBConcurrenceyException.
Here is what I have to tried to clear the table:
private void ClearBut_Click(object sender, EventArgs e)
{
OleDbDataAdapter dtaAdpTestTableClear = new OleDbDataAdapter();
OleDbCommand command;
command = new OleDbCommand("DELETE FROM TestTable", con);
dtaAdpTestTableClear.DeleteCommand = command;
foreach (DataRow row in dsWCSDHDB.Tables["TestTable"].Rows)
{
row.Delete();
}
dtaAdpTestTableClear.Update(dsWCSDHDB.Tables["TestTable"]);
}
My other add method
private void Add_Click(object sender, EventArgs e)
{
OleDbDataAdapter dtaAdpTestTableInsertNewRow = new OleDbDataAdapter();
OleDbCommand command;
// Create the InsertCommand.
// This is needed as DataAdaptor.InsertCommand() is called during the update to insert the row into the database. It requires an insert query
command = new OleDbCommand("INSERT INTO TestTable (id, someData) " +"VALUES (?, ?)", con); //We create a dbcommand the command is, Querytype, what we are doing with it, what table, (columns we are using), concat, Values we will be adding(as ? for now as we will pass this data in latter), connection to the database
command.Parameters.Add("id", OleDbType.Char, 5, "id"); //this is where we add a parameter to the command function. we add one per column in the row (columns we are using name, value type, column length, source column, these parameters will replace the ? in the query above
command.Parameters.Add("someData", OleDbType.VarChar, 40, "someData");
dtaAdpTestTableInsertNewRow.InsertCommand = command;// we attach this command to the Insert command function of the adapter that we are using
//Create the new row
DataRow row = dsWCSDHDB.Tables["TestTable"].NewRow(); //Create a new empty row that is formated for the TestTable table
row["someData"] = AddValueTextBox.Text.ToString();// add in the values
//Add the new row to the dataset table
dsWCSDHDB.Tables["TestTable"].Rows.Add(row); //adds this new row to the clients dataset
//Updates the database table with the values of the clients dataset Table
//For this to work you need to build a proper data adapter that is using a query taylered for the table you are using.
//Unfortunately although it would be nice to be able to add and use tables to the database with out changing the code you cant build a generic one that works for all tables in the database.
//this is because different tables can have different fields and column lengths .
//there is a example of how to build one below
//Update the database table with the values of the clients dataset Table
dtaAdpTestTableInsertNewRow.Update(dsWCSDHDB.Tables["TestTable"]); // using the adapter that we created above we update the database with the clients dataset.
}
You will just need to call ExecuteNonQuery
private void ClearBut_Click(object sender, EventArgs e)
{
string comand = "DELETE FROM TestTable";
OleDbCommand cmd = new OleDbCommand(comand, con);
cmd.ExecuteNonQuery();
}
Related
In this form, I have just one gridcontrol and this datasource is datatable connected to SQL Server.
Bottom of the gridcontrol there are four buttons named select, insert, delete, modify gridcontrol.
This is my code, and it has click event when insert button is clicked.
private void InputButton_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection conn = new SqlConnection(mssql))
{
conn.Open();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("Insert into [Department] (부서코드, 부서명) values (#부서코드, #부서명)", conn);
cmd.Parameters.AddWithValue("#부서코드", "2101");
cmd.Parameters.AddWithValue("#부서명", "영업부");
sqlDataAdapter.InsertCommand = cmd;
int result = cmd.ExecuteNonQuery();
if (result < 0)
{
MessageBox.Show("There are errors when inserting data");
}
else
{
sqlDataAdapter.Update(dataTable);
gridControl1.RefreshDataSource();
conn.Close();
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When I click insert button, there are not any event in gridcontrol so I don't see any change of insert query. However, close form and reopen form, then I can see my insert query in gridcontrol.
Even I use gridcontrol.refreshdatasource but I don't know what I can't see any changes soon after I click
insert button. Is there any answers?
Even I tried use try catch, but I don't know my issue. I want to show gridcontrol.refreshdatasource when I click insert query.
To insert SQL Server data using a GridControl and DataTable in C# Winform, you can follow these steps:
Create a connection string to connect to the SQL Server database. You can use the SqlConnection class to create the connection string.
string connectionString ="Server<server_name>;Database<database_name>;User Id=<username>;Password=<password>;";
Create a DataTable object to store the data that will be displayed in the GridControl. You can add columns to the DataTable object to match the columns in the SQL Server table.
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
Create a SqlDataAdapter object and use it to fill the DataTable object with data from the SQL Server table. You can use the SELECT statement to retrieve the data.
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM <table_name>", connectionString);
adapter.Fill(dt);
Set the DataSource property of the GridControl to the DataTable object to display the data in the GridControl.
gridControl1.DataSource = dt;
Add a new row to the DataTable object using the NewRow method, and set the values of the columns.
DataRow row = dt.NewRow();
row["ID"] = 1;
row["Name"] = "Bob Ross";
row["Age"] = 52;
dt.Rows.Add(row);
Create a SqlCommand object to insert the data into the SQL Server table. You can use the INSERT INTO statement to insert the data.
SqlCommand cmd = new SqlCommand("INSERT INTO <table_name> (ID, Name, Age) VALUES (#ID, #Name, #Age)", connection);
cmd.Parameters.AddWithValue("#ID", row["ID"]);
cmd.Parameters.AddWithValue("#Name", row["Name"]);
cmd.Parameters.AddWithValue("#Age", row["Age"]);
cmd.ExecuteNonQuery();
Refresh the DataTable object and the GridControl to reflect the changes.
dt.Clear();
adapter.Fill(dt);
gridControl1.RefreshDataSource();
Note that you should handle any exceptions that may occur while inserting data into the SQL Server table, and also make sure to dispose of any database connections, commands, and adapters after use.
Hope this helps.
On one form I have a dgv. From another form, I can add an item to the dgv and also place the new item into the SQLite database.
What I'm trying to do is also be able to edit the item from the dgv, and have the edit be saved in the database also.
I have this code for CellEndEdit event:
SetConnection();
sqlconnection.Open();
this.dataGridView1.Rows[e.RowIndex].Selected = true;
this.rowIndex1 = e.RowIndex;
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[0];
sqlcmd = new SQLiteCommand("UPDATE table1 SET item = #item, quantity = #quantity WHERE id= " + this.dataGridView1.Rows[this.rowIndex1].Cells["id"].Value, sqlconnection);
sqlcmd.Parameters.AddWithValue("#item", this.dataGridView1.Rows[this.rowIndex1].Cells["item1"].Value);
sqlcmd.Parameters.AddWithValue("#quantity", this.dataGridView1.Rows[this.rowIndex1].Cells["quantity1"].Value);
sqlcmd.ExecuteNonQuery();
sqlconnection.Close();
This code works, but only if I load the database to the dgv.
When the program is first opened, the database isn't loaded into the dgv. The problem I run into, is when I add a new item (and its the only item present in the dgv), and I try to edit it (aka. change name.etc.), I get the following error: SQL logic error or missing database
near " ": syntax error
Note: When the dgv is empty and I add a new item, the new item is successfully added to the database table.
Also Note: 'id' is the PRIMARY KEY and AUTOINCREMENTed
The situation you're having here is that when you add a new item to the DGV, you are not providing a value to the ID column. So at the end of the query
"UPDATE table1 SET item = #item, quantity = #quantity WHERE id= " + this.dataGridView1.Rows[this.rowIndex1].Cells["id"].Value
This will become like id = . because the ID column in the DGV is currently empty and is definitely a Syntax Error.
It works when you load data because, you are filling up this column. So the solution is to provide value to the ID column properly when you insert a new item.
After inserting an entry to the db, get the Automatically Incremented ID by using a query
Select last_insert_rowid();
Read the value using reader and apply it to the ID column of the table
This works for me.
private void btnUpdate_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Server=your_server_name;Database=your_db_name;Trusted_Connection=True;"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Courses", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
{
SqlCommandBuilder sqlcmd = new SqlCommandBuilder(da);
DataSet ds = new System.Data.DataSet(); // remove this line
da.Update(this.ds, "Courses");
}
}
}
}
}
I'm filling a Data Grid in C# (WinForms) via a System.Data.DataTable. DataTable is filled from a DB table via ODP.
I have a data navigator in Data Grid for updating, deleting and inserting rows.
I want to use DataTable to commit all changes made in Data Grid to the database.
I have to use OracleDataAdapter but I couldn't figure out how to achieve this.
What kind of a CommandText should I use to achieve all three commands (update, delete, insert)?
The code below didn't work (maybe because CommandText I inserted is not appropriate)
public void ExecuteNonQuery(string commandText, OracleCommand oracleCommand, CommandType commandType, DataTable dataTable)
{
oracleCommand.CommandText = commandText;
oracleCommand.CommandType = commandType;
try
{
oracleCommand.Connection = m_Connection;
OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(oracleCommand);
oracleDataAdapter.Update(dataTable);
}
catch (Exception)
{
LoggerTrace.Instance.Write(TraceEventType.Error, LoggerTrace.LoggerTraceSource.DatabaseManagerError, "Query could not be executed!");
throw;
}
}
for insert create a new row in data table and insert into data table ,for update update the value and finally make save change of data set or data table
OracleCommandBuilder producess the appropriate insert, update and delete queries after the select query is inserted.
string selectCommand = "select * from Table";
oracleDataAdapter.SelectCommand = new OracleCommand(selectCommand, m_Connection);
OracleCommandBuilder cmdBuilder = new OracleCommandBuilder(oracleDataAdapter);
DataTable dataTable = new DataTable();
oracleDataAdapter.Fill(dataTable);
After OracleCommandBuilder build the command this way you can execute any updates in the DataTable like this:
oracleDataAdapter.Update(dataTable);
Sequences, virtual columns etc. are not allowed.
I have a four column table in a SQL Server database. The info for the first three columns is supplied by another source. Column 4 is set to null by default.
I then have a win form with a datatable that populates with the information from the SQL Server database using the following code:
public DataTable populateFormList()
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.sqlConnectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM of_formlist_raw", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
}
datagridview2.DataSource = populateFormList();
datagridview2.Refresh();
Now that works fine in obtaining my data.
The user can then make changes to the null values in column 4.
How can I easily write these changes from the datatable back into the SQL Server table?
In other words, once the on screen datatable has additional values, how can I then store the updated information back in the SQL Server database from which it was originally obtained from?
Thanks.
Try something like this and just pass (DataTable)datagridview2.DataSource as the data table:
private static void BulkInsertToSQL(DataTable dt, string tableName)
{
using (SqlConnection con = new SqlConnection(_DB))
{
SqlBulkCopy sbc = new SqlBulkCopy(con);
sbc.DestinationTableName = tableName;
//if your DB col names don’t match your data table column names 100%
//then relate the source data table column names with the destination DB cols
sbc.ColumnMappings.Add("DBAttributeName1", "DTColumnName1");
sbc.ColumnMappings.Add("DBAttributeName2", "DTColumnName2");
sbc.ColumnMappings.Add("DBAttributeName3", "DTColumnName3");
sbc.ColumnMappings.Add("DBAttributeName4", "DTColumnName4");
con.Open();
sbc.WriteToServer(dt);
con.Close();
}
}
2 options, with or without TableAdapter.
I would recommend to read this in MSDN for TableAdapter
They're using BindingSources too, which are excellent components, easy-to-use.
Without TableAdapter, read this, the "Update Records Using Command Objects" part.
I'm trying to learn some C#.net. I'm just trying to expose the AdventureWorks database included in my C# class via a web interface. Here's the setup:
I've got a DropDownList in on my ASPX page with an id of tableNameDropDown. It gets populated on Page_Load like this:
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
String table_names_sql = "select Name from sysobjects where type='u' ORDER BY name";
SqlCommand cmd = new SqlCommand(table_names_sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
tableNameDropDown.Items.Add(reader[0].ToString());
}
conn.Close();
tableNameDropDown.AutoPostBack = true;
}
And that works just fine, I get a nice long list of the tables in the DB. When someone selects a table from the list, I want to display that table in a GridView control with an id of grid. This is what I've got:
protected void tableNameDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dataSet = new DataSet();
String tableName = columnNameDropDown.SelectedItem.ToString();
String table_sql = String.Format("SELECT * FROM {0};", tableName);
SqlDataAdapter adapter = new SqlDataAdapter(table_sql, conn);
adapter.Fill(dataSet, tableName);
grid.DataSource = dataSet;
grid.DataMember = tableName;
}
When I debug the page, I get an error on the adapter.Fill(dataSet, tableName); line: SqlException: Inlvalid object name '{tableName}'.
The tables in the DB are the following:
dbo.AWBuildVersion
.... more dbo. tables
HumanResources.Department
HumanResources.Employee
.... more HumanResources tables
Person.Address
Person.AddressType
.... more Person tables
... Other prefixes are "Pdoduction, Purchasing, Sales"
There are probably ~50+ tables, and I get all their names (without the prefixes) into my DropDownList no problem, but I can't seem to query them.
Any ideas?
You've already answered yourself: you need to use also the prefix in the select statement you're executing, like
Select * From Person.Address
Beside that you should not use the sysobject tables, from SQL Server 2005 you have system views that helps you, so you can write a better statement to select tables:
select * From INFORMATION_SCHEMA.TABLES
Check also this article.
Regards
Massimo