I need to know what the size parameter should be for a DateTime value using the following syntax:
adapter.InsertCommand.Parameters.Add("#deliveryDateAndTime", SqlDbType.DateTime,10,"deliveryDateAndTime");
I cannot use the following syntax because I'm batching the updates in a datatable.
adapter.InsertCommand.Parameters.Add("#deliveryDateAndTime", SqlDbType.DateTime);
adapter.InsertCommand.Parameters["#deliveryDateAndTime"] = *variable*.value;
Below is the code I need to use (abbreviated for clarity). Note that inside the adapter.InsertCommand.Parameters.Add("#deliveryDateAndTime", SqlDbType.DateTime,10,"deliveryDateAndTime"); statement, the first parameter refers to a corresponding SQL parameter and the 4th parameter corresponds to the data for that value inside the datatable.
DataTable dt = new DataTable();
foreach (FuelDelivery fd in fuelDelivery.FuelDeliveries)
{
DataRow dr = dt.NewRow();
dr["deliveryDateAndTime"] = fd.DeliveryDateAndTime;
dt.Rows.Add(dr);
}
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HHSqlConnection"].ToString()))
{
// Create a SqlDataAdapter.
SqlDataAdapter adapter = new SqlDataAdapter();
// Set the INSERT command and parameter.
adapter.InsertCommand.Parameters.Add("#deliveryDateAndTime", SqlDbType.DateTime,10,"deliveryDateAndTime");
adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None;
// Set the batch size. Zero represents the maximum amt of rows to update at once.
adapter.UpdateBatchSize = 0;
// Execute the update.
int rowsUpdated = adapter.Update(dt);
}
Based on this overload for the adapter.InsertCommand.Parameters.Add method, how can I set the date accordingly?
A datetime is 8 bytes according to the easily searchable documentation.
Note that you could also use your preferred overload and set the source column separately:
adapter.InsertCommand.Parameters.Add("#deliveryDateAndTime", SqlDbType.DateTime)
.SourceColumn = "deliveryDateAndTime";
Related
i want to create a for loop in which i want to write a query which updates the the value of each row in database. the rows are present in the datagridview as well as in the database. the aim is when the changes are made in datagridview so using a button the change are also applied in the database table too. in each row the barcode and its quantity is different. if the changes are made in all the rows in datagridview so it is also to be applied in database using button and also please help with the parameters.
here is the query which should be considered in the for loop:
SqlCommand cmd2 = new SqlCommand("update prod_info set item_quantity=#qty where barcode=#barcode ", con);
consider barcode as column1 and item_quantity as column2.
so far to create a for loop i have tried this but getting error in the for loops:
for (int i = 0; dataGridView2.Rows.Count; i++) //getting error here
{
SqlCommand cmd2 = new SqlCommand("update prod_info set item_quantity=#qty where barcode=#barcode ", con);
cmd2.Parameters.AddWithValue("#barcode", dataGridView2.Rows[i].Cells[1].Value.ToString());
cmd2.Parameters.AddWithValue("#qty", dataGridView2.Rows[i].Cells[1].Value.ToString());
}
you should call cmd2.ExecuteNonQuery(); in your loop ... otherwise no sql commands will be executed
to get a better solution you should move to creation of cmd2 before the loop. also add the parameters there (without assigning values) ... inside the loop just assign the values and call ExecuteNonQuery.
maybe the best solution would be to use databinding and a SqlDataAdapter with assigned UpdateCommand.
just saw that there probably is an error in your code ... you use the value from Cell[1] for both of your parameters ...
example:
first create a DataTable ... var dt = new DataTable();
then add the columns you want in your grid to the DataTable ... dt.Columns.Add("xyz");
then attach the DataTable to your grid: dataGridView2.DataSource = dt;
now you should be able to edit the contents of column "xyz". to write the values to the database you create a SqlDataAdapter ... var adp = new SqlDataAdapter();
then set adp.InsertCommand = new SqlCommand(...) and adp.UpdateCommand = new SqlCommand(...)
now you can call adp.Update(); and all the values from your grid are written to db ... for newly added rows the InsertCommand is invoked and for edited rows the UpdateCommand is invoked.
I am new in net I want to use data table instead of a database.
I want to know that why is data table query different from an sql query?
I want to find a value from data table:
SELECT dbo.General_Ledger.Entry_Amount FROM dbo.General_Ledger WHERE Account_number=lbDebit_Account_numer
and
using (SqlConnection connect = new SqlConnection(con))
{
int index = lbDebit_Account.FindString(txtDebit_Account.Text);
if (0 <= index)
{
lbDebit_Account.SelectedIndex = index;
}
SqlDataAdapter da3 = new SqlDataAdapter("SELECT *FROM dbo.General_Ledger", connect);
DataTable dt1 = new DataTable();
da3.Fill(dt1);
string lbDebit_Account_numer = lbDebit_Account.SelectedValue.ToString();
string row;
row= Convert.ToString(dt1.Select(string.Format("'Account_number'={0}",lbDebit_Account_numer)));
}
I want to perform this query:
SELECT dbo.General_Ledger.Entry_Amount FROM dbo.General_Ledger WHERE Account_number=lbDebit_Account_numer
So you'll want to parameterize your query:
SqlDataAdapter da3 = new SqlDataAdapter("SELECT * FROM dbo.General_Ledger WHERE Account_number = #Account_number");
da3.SelectCommand.Parameters.AddWithValue("#Account_number", lbDebit_Account.SelectedValue);
DataTable dt1 = new DataTable();
da3.Fill(dt1);
and now you'll have just the one row you want and you can recover it like this:
DataRow dr = dt1.Rows[0];
and then you can grab values off of that row a number of different ways:
var val = dr[0]; // grabs the value of the first column in the result list
var val = dr["fieldname"] // grabs the value of a specific field name
and there are even some methods that will returned typed data because the aforementioned return an object since the underlying value could be a number of things. So, if it were a string field you were after you could do something like:
var val = dr.Field<string>(0) // grabs the value of the first column and returns it typed as a string
var val = dr.Field<string>("fieldname") // grabs a field and returns it typed as a string
It very simple, u want to filter the DataTable[dt1] base on this string[lbDebit_Account_numer]
DataRow dr = dt1.Select("Account_number = '"+lbDebit_Account_numer ="'");
u can use
AND OR
operators
single code['] need for string variables to compare.
here u get data-row, all cell will in an array format you select any cell.
You can try to use DefaultView.RowFilter property of DataTable class.
Example:
dataTable.DefaultView.RowFilter = "Account_number=1";
I am attempting to loop through a dataset's rows and columns in search for a match between the dataset's name column -- and the ColumnName from a DataReader object.
I have a new table called RECORDS which is empty at program startup. I also have a pre-populated table called ColumnPositions with a sub-set of column names found in the RECORDS table. This routine is intended to show a subset of all the available columns -- as a default display style.
My code works...except for the line of code that gets the dr["type"] value. I get the error:
The name 'colType' does not exist in the current context.
As you can clearly see, my string variables are declared outside the WHILE and FOREACH loops. The line statement colName = works just fine. But colType fails everytime. If I do a statement check in the Intermediate Window in VS2010 for ? dr["type"]" I get the result integer. But when I check ? colType, I get the above noted error message.
The intellisense for the DataRow object dr reveals an array of 6 items. Index 1 in the array maps to name. Index 2 maps to type. When I check the value of ? dr[2] in the Intermediate Window, the same result comes back integer. This is correct. But whenever this value is assigned to colType, VS2010 complains.
I'm no newbie to C# so I did a lot of testing and Googling before posting here. I'm hoping that this is a matter of me not seeing the forest through the trees.
Here's my code:
// get table information for RECORDS
SQLiteCommand tableInfo = new SQLiteCommand("PRAGMA table_info(Records)", m_cnCaseFile);
SQLiteDataAdapter adapter = new SQLiteDataAdapter(tableInfo);
DataSet ds = new DataSet();
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM ColumnPositions WHERE ColumnStyle_ID = " + styleID + " ORDER BY ColumnPosition_ID ASC", m_cnCaseFile);
SQLiteDataReader colReader = cmd.ExecuteReader();
string colName = "";
string colType = "";
if (dt != null && colReader.HasRows)
{
while (colReader.Read())
{
foreach(DataRow dr in dt.Rows)
{
colType = Convert.ToString(dr["type"]);
colName = dr["name"].ToString();
if (colReader["ColumnName"].ToString() == colName)
{
DataGridViewColumn dgvCol = new DataGridViewColumn();
}
}
}
}
dt.Dispose();
colReader.Close();
Instead of using "dr["name"].ToString();", it is better to use "Convert.ToString(dr["name"]);"
Try using the array position instead of the column name:
colType = Convert.ToString(dr[1]);
and
colName = dr[0].ToString();
You probably don't need this, but here is the documentation for values returned by the SQLite PRAGMA table_info() command. LINK
I have a table which has some 100-200 records.
I have fetch those records into a dataset.
Now i am looping through all the records using foreach
dataset.Tables[0].AsEnumerable()
I want to update a column for each record in the loop. How can i do this. Using the same dataset.
I'm Assumng your using a Data Adapter to Fill the Data Set, with a Select Command?
To edit the data in your Data Table and save changes back to your database you will require an Update Command for you Data Adapter. Something like this :-
SQLConnection connector = new SQLConnection(#"Your connection string");
SQLAdaptor Adaptor = new SQLAdaptor();
Updatecmd = new sqlDbCommand("UPDATE YOURTABLE SET FIELD1= #FIELD1, FIELD2= #FIELD2 WHERE ID = #ID", connector);
You will also need to Add Parameters for the fields :-
Updatecmd.Parameters.Add("#FIELD1", SQLDbType.VarCHar, 8, "FIELD1");
Updatecmd.Parameters.Add("#FIELD2", SQLDbType.VarCHar, 8, "FIELD2");
var param = Updatecmd.Parameters.Add("#ID", SqlDbType.Interger, 6, "ID");
param.SourceVersion = DataRowVersion.Original;
Once you have created an Update Command with the correct SQL statement, and added the parameters, you need to assign this as the Insert Command for you Data Adapter :-
Adaptor.UpdateCommand = Updatecmd;
You will need to read up on doing this yourself, go through some examples, this is a rough guide.
The next step is to Enumerate through your data table, you dont need LINQ, you can do this :-
foreach(DataRow row in Dataset.Tables[0].Rows)
{
row["YourColumn"] = YOURVALUE;
}
One this is finished, you need to call the Update() method of yout Data Adapter like so :-
DataAdapter.Update(dataset.Tables[0]);
What happens here, is the Data Adapter calls the Update command and saves the changes back to the database.
Please Note, If wish to ADD new rows to the Database, you will require am INSERT Command for the Data Adapter.
This is very roughly coded out, from the top of my head, so the syntax may be slightly out. But will hopefully help.
You should use original DataAdapter (adapter in code below) that was used to fill DataSet and call Update method, you will need CommandBuilder also, it depends what DB you are using, here is the example for SQL server :
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Update(dataset);
dataset.AcceptChanges();
Here is the good example :
http://support.microsoft.com/kb/307587
The steps would be something like:
- create a new DataColumn[^]
- add it to the data table's Columns[^] collection
- Create a DataRow [^] for example using NewRow[^]
- Modify the values of the row as per needed using Item[^] indexer
- add the row to Rows[^] collection
- after succesful modifications AcceptChanges[^]
Like this:
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("ProductName");
table.Rows.Add(1, "Chai");
table.Rows.Add(2, "Queso Cabrales");
table.Rows.Add(3, "Tofu");
EnumerableRowCollection<DataRow> Rows = table.AsEnumerable();
foreach (DataRow Row in Rows)
Row["ID"] = (int)Row["ID"] * 2;
Add the column like below.
dataset.Tables[0].Columns.Add(new DataColumn ("columnname"));
Update the columns values like below.
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
dataset.Tables[0].Rows[i]["columnname"] = "new value here";
}
Update Database
dataset.AcceptChanges();
I have a postgresql db and a C# application to access it. I'm having a strange error with values I return from a NpgsqlDataAdapter.Fill command into a DataSet.
I've got this code:
NpgsqlCommand n = new NpgsqlCommand();
n.Connection = connector; // a class member NpgsqlConnection
DataSet ds = new DataSet();
DataTable dt = new DataTable();
// DBTablesRef are just constants declared for
// the db table names and columns
ArrayList cols = new ArrayList();
cols.Add(DBTablesRef.all); //all is just *
ArrayList idCol = new ArrayList();
idCol.Add(DBTablesRef.revIssID);
ArrayList idVal = new ArrayList();
idVal.Add(idNum); // a function parameter
// Select builder and Where builder are just small
// functions that return an sql statement based
// on the parameters. n is passed to the where
// builder because the builder uses named
// parameters and sets them in the NpgsqlCommand
// passed in
String select = SelectBuilder(DBTablesRef.revTableName, cols) +
WhereBuilder(n,idCol, idVal);
n.CommandText = select;
try
{
NpgsqlDataAdapter da = new NpgsqlDataAdapter(n);
ds.Reset();
// filling DataSet with result from NpgsqlDataAdapter
da.Fill(ds);
// C# DataSet takes multiple tables, but only the first is used here
dt = ds.Tables[0];
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
So my problem is this: the above code works perfectly, just like I want it to. However, if instead of doing a select on all (*) if I try to name individual columns to return from the query I get the information I asked for, but rather than being split up into seperate entries in the data table I get a string in the first index of the data table that looked something like:
"(0,5,false,Bob Smith,7)"
And the data is correct, I would be expecting 0, then 5, then a boolean, then some text etc. But I would (obviously) prefer it to not be returned as just one big string.
Anyone know why if I do a select on * I get a datatable as expected, but if I do a select on specific columns I get a data table with one entry that is the string of the values I'm asking for?
Ok, I figured it out, it was in the SelectBuilder function. When more than one column was listed in the select statement it was wrapping the columns in ()'s, and apparently this causes either postgreSQL or Npgsql to interpret that as a desire to return a list in string form.