When I add data to my SQLite database table using the below code, it adds 2 identical rows to the table for some reason instead of one.
using(SQLiteConnection conn= new SQLiteConnection(#"Data Source="+Path.GetFullPath("./TestDB.db")+";"))
{
conn.Open();
SQLiteCommand command = new SQLiteCommand("INSERT INTO Test(FirstName, LastName, Age) VALUES('Chris','Pine',42)", conn);
command.ExecuteNonQuery();
SQLiteDataAdapter adap = new SQLiteDataAdapter(command);
DataTable dt = new DataTable("Test");
adap.Fill(dt);
dataGrid1.ItemsSource=dt.DefaultView;
adap.Update(dt);
conn.Close();
}
MessageBox.Show("Complete!");
refreshdata();
Why is this happening ?
Also, the code for refreshdata
public void refreshdata()
{
using(SQLiteConnection conn= new SQLiteConnection(#"Data Source="+Path.GetFullPath("./TestDB.db")+";"))
{
conn.Open();
SQLiteCommand command = new SQLiteCommand("Select * from Test", conn);
command.ExecuteNonQuery();
SQLiteDataAdapter adap = new SQLiteDataAdapter(command);
DataTable dt = new DataTable("Test");
adap.Fill(dt);
dataGrid1.ItemsSource=dt.DefaultView;
adap.Update(dt);
conn.Close();
}
You are calling ExecuteNonQuery and you are giving the adapter an INSERT command in place of its SelectCommand.
SQLiteDataAdapter adap = new SQLiteDataAdapter(command);
That line of code uses a the constructor that sets the adapter's SelectCommand. When you Fill() the datatable, it calls the SelectCommand, but in your case it is an INSERT statement.
Really, you should not be doing anything with an Adapter there, you should just ExecuteNonQuery and then call refreshdata.
And you can remove the call to Update() in refreshdata(), it is not necessary.
Related
I have a 'Create new Order' Form where I create an order which once created in now on the DB Table displayed in a datagridView.
However I am struggling to get the datagridView to auto update with the new data in it.
This is the form:
This is the table where the new order should be displaying. However only displays when i switch tables and not when the New order is created successfully.
I have tried the dataGridView.Refresh() and a bunch of other researched solutions but non seem to work.
This is my Code.
MySqlConnection conn = new MySqlConnection();
conn.Close();
var x = inputOrderTitle.Text;
Random rnd = new Random();
try
{
MySqlConnection mysqlConnection = new MySqlConnection();
connect.OpenSuccessfulDBConnection(mysqlConnection);
String query = "INSERT INTO tb_orders VALUES (#order_id, #title, #description, #scheduled_date, #deadline_date, #word_count, #editor_url, #status, #is_complete, #is_invoiced, #is_closed, #type, #ClientID, #InvoiceID, is_inprogress, #client_name, #order_cost)";
MySqlCommand cmd = new MySqlCommand(query, mysqlConnection);
cmd.Parameters.AddWithValue("#order_id", "BLG0556");
cmd.Parameters.AddWithValue("#title", "abc");
cmd.Parameters.AddWithValue("#description", "abc");
cmd.Parameters.AddWithValue("#scheduled_date", dateTimeSchedDate.Value.Date);
cmd.Parameters.AddWithValue("#deadline_date", dateTimeSubDate.Value.Date);
cmd.Parameters.AddWithValue("#word_count", 123);
cmd.Parameters.AddWithValue("#editor_url", "abc");
cmd.Parameters.AddWithValue("#status", "abc");
cmd.Parameters.AddWithValue("#is_complete", 0);
cmd.Parameters.AddWithValue("#is_invoiced", 0);
cmd.Parameters.AddWithValue("#is_closed", 0);
cmd.Parameters.AddWithValue("#type", comboBoxOrderType.Text);
cmd.Parameters.AddWithValue("#ClientID", 123);
cmd.Parameters.AddWithValue("#InvoiceID", 432);
cmd.Parameters.AddWithValue("#is_inprogress", 1);
cmd.Parameters.AddWithValue("#client_name", "abc");
cmd.Parameters.AddWithValue("#order_cost", 30.00);
int result = cmd.ExecuteNonQuery();
Application.OpenForms
.OfType<Form>()
.Where(form => String.Equals(form.Name, "NewOrder"))
.ToList()
.ForEach(form => form.Close());
MessageBox.Show("Order created successfully.");
orders.dataGridViewOrderList.Rows.Clear();
connect.GetOrderList(orders.dataGridViewOrderList);
}
Use the 'DataSource' property to bind the grid to the bunch of fetched data
SqlConnection mysqlConnection = new SqlConnection("your connection string");
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select * from tb_orders(nolock)", mysqlConnection);
if (mysqlConnection.State == ConnectionState.Closed)
mysqlConnection.Open();
da.SelectCommand.ExecuteNonQuery();
da.Fill(dt);
dataGridViewOrderList.DataSource = dt;
my method is:
{
conn.Open();
SqlCommand cmd = new SqlCommand
("select BusinessEntityID from Person.Person order by'BusinessEntityID' ASC", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr["BusinessEntityID"]);
}
conn.Close();
}
but that's not what I want. I have a class. update, insert, and delete list that also includes methods. a draw method of the ComboBox here I write data in the form side of the DataSource of the ComboBox I can I take it? In my system, every time the form on the side, I am forced to open and close connections.
for example, I take like DataGridView data
class side
public DataTable list()
{
SqlDataAdapter da = new SqlDataAdapter
("select * from HumanResources.Employee", OpenConnection());
DataTable dt = new DataTable();
DataSet ds = new DataSet();
da.Fill(dt);
CloseConnection();
return dt;
}
form side
dataGridView1.DataSource = data.list();
How can I save a DataTable to a file. accdb (Access) existing one? I've used the following code and it does not work:
using (OleDbConnection oledbConnection = new OleDbConnection(connection))
{
oledbConnection.Open();
string query = "SELECT * FROM Student";
using (OleDbCommand oledbCommand = new OleDbCommand(query, oledbConnection))
{
using (OleDbDataAdapter oledbDataAdapter = new OleDbDataAdapter(oledbCommand))
{
using (OleDbCommandBuilder oledbCommandBuilder = new OleDbCommandBuilder(oledbDataAdapter))
{
oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand(true);
oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand(true);
oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand(true);
oledbDataAdapter.Update(dataTable);
}
}
}
oledbConnection.Close();
}
The variable dataTable is initialized with the original contents of the file, then it was modified by adding a row and now I have to update the table in the database.
I tried using the following code, but that does not work :(
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Student", connection);
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(da);
da.InsertCommand = cmdBuilder.GetInsertCommand(true);
// create and insert row in the DataTable
da.Update(dataTable);
Assuming that you have made some changes in the datatable, then you could pass the generated update/insert/delete command to the adapter in this way
oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand();
oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand();
oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand();
oledbDataAdapter.Update(datatable);
Now the adapter knows how to update your table
What is the code with the smallest number of lines that will generate a DataTable from this SQL query?
SELECT *
FROM [Table1]
WHERE ([Date] BETWEEN #Date1 AND #Date2) AND
([Field1] IS NULL OR [Field2] IS NULL)
Use SqlDataAdapter to fill a DataTable.
DataTable dt = new DataTable();
using (SqlConnection yourConnection = new SqlConnection("connectionstring"))
{
using (SqlCommand cmd = new SqlCommand("....your sql statement", yourConnection))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
Use using block with your SqlConnection, SqlCommand and SqlDataAdapter since they implement IDisposable interface. Also use Parameterized query
Try this
SqlCommand command = new SqlCommand(query, conn);
DataTable dt = new DataTable();
using(SqlDataReader reader = command.ExecuteReader())
{
dt.Load(reader);
}
SqlDataAdaptor and FillSchema
It will create your table on the fly
Applied On a DataSet
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx
Applied On a DataTable
http://msdn.microsoft.com/en-us/library/152bda9x.aspx
private void FillInvoiceList()
{
DataTable distinctInvoice = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["APOS_CONNECTION_STRING"].ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select distinct svc_tag from data where rep_name = #value");
cmd.Parameters.AddWithValue("#value", this.DropDownList1.SelectedItem.Text);
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd.CommandText, conn.ConnectionString);
sqlDataAdapter.Fill(distinctInvoice);
}
foreach (DataRow row in distinctInvoice.Rows)
{
this.ListBox1.Items.Add(row["svc_tag_dim_invoice_num"].ToString());
}
}
I have this code and I get this error when I call the Fill(DistinctInvoice)
Must declare the scalar variable "#value"
My FillInvoiceList() Method is being called from a SelectedIndexChanged event from the DropDownList1. The value of DropDownList1.SelectedItem.Text seems to be correct.
Thanks for any help.
The error is here :
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd.CommandText, conn.ConnectionString);
You're setting the SQLDataAdapter to use the original CommandText, not the SQLCommand itself. Change it to :
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd, conn.ConnectionString);