i have simple table item and a text box textbox1 now i want to show max value in textbox i am using the command but code not work
item table: CREATE TABLE TableItem( ItemId NUMBER(10) NOT NULL,
ItemName VARCHAR2(40) NOT NULL, UnitId NUMBER(10) NOT NULL,
CategoryId NUMBER(10) NOT NULL, ItemStatus NUMBER(1) NOT NULL,
SupplierId NUMBER(10)NOT NULL );
and item table insert data:
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(01,'Product-1',21,10,1,51);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(02,'Product-2',22,11,1,52);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(03,'Product-3',23,12,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(04,'Product-4',24,14,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(05,'Product-5',21,12,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(06,'Product-5',23,12,1,52);
now i need max value of itemid
con.Open();
try
{
OleDbCommand cmd4 = new OleDbCommand("SELECT MAX(ItemId) FROM TableItem", con);
textBoxInsert.Text = cmd4.ExecuteScalar().ToString();
}
finally
{
}
con.Close();
You need to create a data adapter, it will fetch your SQL in your database based on your connection. After that you will get a table as result, so you just need to add it to your DataTable and get the rows. There is more interesting implementations, but with this code you can see if it everything is working fine, I've implemented a MySQL version like this:
DataTable _datatable = new DataTable();
MySQLDataAdapter _adapter = new MySQLDataAdapter("SELECT * FROM TEST_TABLE", connection)
_adapter.Fill(_datatable);
myTextBox.Text = _datatable.Rows[0]["ID"].ToString();
On your case, you just need to replace MySQLDataAdapter with OracleDataAdapter, from OracleClient
Reference:
https://msdn.microsoft.com/pt-br/library/system.data.oracleclient.oracledataadapter(v=vs.110).aspx
It is simple. We took the double result for the number we will get in the database.
using (MySqlCommand cmd = new MySqlCommand("SELECT MAX(ItemId) FROM TableItem", con))
{
con.Open();
double result = (Convert.ToDouble(cmd.ExecuteScalar()));
textBoxInsert.Text = result.ToString();
}
Related
SqlCeCommand command = new SqlCeCommand(#"INSERT INTO fpl_table
(FLIGHT_ID, BPN_TIME, BPX_TIME, DAY_NB)
VALUES (#FLIGHT_ID, #BPN_TIME, #BPX_TIME, #DAY_NB)
ON DUBLICATE UPDATE FLIGHT_ID = #FLIGHT_ID, BPN_TIME=#BPN_TIME,BPX_TIME=#BPX_TIME,DAY_NB=#DAY_NB"
,connection);
command.Parameters.AddWithValue("FLIGHT_ID", format);
command.Parameters.AddWithValue("BPN_TIME", format1);
command.Parameters.AddWithValue("BPX_TIME", format2);
command.Parameters.AddWithValue("DAY_NB", format3);
Hi everyone!
Ive got the problem with inserting 4 values into columns. I wanna prevent inserting 4 existing columns into database, i cant set them unique, cause the same column can be inserted with other 1,2 or 3 columns, i just wanna prevent only 4 existing columns insert.
you can add a unique constraint on 4 columns
CONSTRAINT UC_unique UNIQUE (col1, col2, col3, col4)
https://www.w3schools.com/sql/sql_unique.asp
Why not you use a seperate function to find out duplicate records at first.
bool CheckDuplicateFlight(int FLIGHT_ID)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"YOURCONNECTION STRING";
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
SqlCeCommand cmd = new SqlCeCommand("select count(*) from YOURTABLE where FLIGHT_ID= #FLIGHT_ID", con);
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#FLIGHT_ID",FLIGHT_ID);
int ExistingId= Convert.ToInt32(cmd.ExecuteScalar());
}
con.Close();
if(ExistingId> 0)
return true;
return false;
}
if(CheckDuplicateFlight(FLIGHT_ID))
{
///// Your insertion/Update Code here
}
But Your Question is confusing a bit, Are you sure you want to insert record instead of update??? Insert query always inserts new record.
You need to add Unique Constraints to 3 columns, and than using exception handling at your code, insert new record.
I'm getting this error message: Cannot insert the value NULL into column 'id', table ''; column does not allow nulls. INSERT fails. thanks in advance
protected void AddItem(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO Picture (Album, id) VALUES (#Album, #id)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
}
I suppose that ID is an IDENTITY column. Its value is generated automatically by the database engine and you want to know what value has been assigned to your record.
Then you should change your query to
string insertCmd = #"INSERT INTO Picture (Album) VALUES (#Album);
SELECT SCOPE_IDENTITY()";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
int newID = Convert.ToInt32(myCommand.ExecuteScalar());
}
The query text now contains a second instruction SELECT SCOPE_IDENTITY() separated from the first command by a semicolon. SCOPE_IDENTITY returns the last IDENTITY value generated for you by the database engine in the current scope.
Now the command is run using the ExecuteScalar to get back the single value returned by the last statement present in the query text without using any output parameter
I would think that ID is identity. You don't have to add this value. I would try the following code and check the database if you get automatically an ID.
string insertCmd = "INSERT INTO Picture (Album) VALUES (#Album)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.ExecuteNonQuery();
}
I case you want to set the id yourself(withoud automatic increment from the db), you should change the schema of the database removing identity from ID as shown below:
I hope this helps
If you need to stay this column empty you can try to replace to ' '(blank). This will work if you column is not "Key"
Or try to use:
substitute a value when a null value is encountered
NVL( string1, replace_with )
You can do this using stored procedure. Below is the script for Create stored procedure.
CREATE PROCEDURE [dbo].[InsertIntoPicture]
#Album varchar(500)=null,
#id int=0 output
AS
BEGIN
insert INTO Picture(Album)VALUES(#Album)
SET #id=##IDENTITY
END
Below is the code for call stored procedure with C# .
string insertCmd = "InsertIntoPicture";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
Using above code you can insert a date from TextBox and also get last inserted record ID as an output variable as per your requirement.
Thanks .
I am learning how to work with SQL in C#, and I got in troubles with using SqlDataAdapter. I have tried to use direct queries via SqlCommand class and everything works fine, but when I rewrote my code to use SqlDataAdapter I have no changes in my table. There is my code:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ADO"]
.ConnectionString);
connection.Open();
SqlDataAdapter daUser = new SqlDataAdapter("SELECT * FROM Books", connection);
SqlCommand insert = new SqlCommand();
insert.Connection = connection;
insert.CommandText = "INSERT INTO Books (name, author) VALUES (#name, #author);";
SqlParameterCollection pc = insert.Parameters;
pc.Add("#name", SqlDbType.VarChar, 20, "test123");
pc.Add("#author", SqlDbType.VarChar, 20, "test322");
daUser.InsertCommand = insert;
DataSet ds = new DataSet();
daUser.Fill(ds, "Books");
daUser.Update(ds, "Books");
Table Books was created with this SQL query in SQL Server Management Studio:
CREATE TABLE Books
(
id int PRIMARY KEY IDENTITY(1,1),
name varchar(MAX) NOT NULL,
author varchar(MAX) NOT NULL
)
INSERT INTO Books(name, author)
VALUES('1984', 'George Orwell'), ('Fathers and sons', 'Dostoevski')
Looks like I am missing something to do, that why my code have no effect on table.
SqlDataAdapter.Update will call its InsertCommand only for the rows of datatable having RowState = DataRowState.Added.
This rowstate is automatically assigned to the datarows being added to rows collection using DataTable.Add method (until next call to AcceptChanges method). Also you can use DataRow.SetAdded method to force this state assignment.
Since you're not modifying/adding anything in you datatable after you've populated it with select command, it has nothing to insert.
Change your code to something like
daUser.Fill(ds, "Books");
var newBook = daUser.Tables[0].NewRow();
newBook["name"] = "New Book";
newBook["author"] = "Author Name";
daUser.Tables[0].Rows.Add(newBook);
daUser.Update(ds, "Books");
and in this case it should be new row added to the database table.
See MSDN for reference.
Just to clarify the previous answer, which is correct, you want to call ExecuteNonQuery() on the command not the dataAdapter.
SqlCommand insert = new SqlCommand();
insert.Connection = connection;
insert.CommandText = "INSERT INTO Books (name, author) VALUES (#name,
#author);";
SqlParameterCollection pc = insert.Parameters;
pc.Add("#name", SqlDbType.VarChar, 20, "test123");
pc.Add("#author",
SqlDbType.VarChar, 20, "test322");
// you do not need this line if you execute the insert on the command object.
// daUser.InsertCommand = insert;
//Add this line instead:
insert.ExecuteNonQuery();
Joey
I have a table("Product_Location") with the following columns:
ProductID (PK), LocationID (PK), Quantity
i would like to update the table in the database from rows in a datatable. if row already exists then Update quantity otherwise Insert new row.
i have the following method which update the quantity in the table, if the combination of productID and LocationID exists, it just update otherwise insert new row for that combination. code:
public bool UpdateLocationQuantity(DataSet productLocationData,
SqlTransaction sqlTransaction)
{
try
{
bool result = true;
SqlCommand command = new SqlCommand();
//get the Transaction table which contains rows to update from dataset
DataTable table = productLocationData.Tables["Inventory_Transactions"];
//Create Command Text
string commandText = #" IF Exists (SELECT * FROM Product_Location PL
WHERE ProductID = #ProductID AND LocationID = #LocationID)
UPDATE Product_Location SET Quantity = Quantity + #Quantity
WHERE ProductID = #ProductID AND LocationID = #LocationID
ELSE
INSERT INTO Product_Location (ProductID,LocationID,Quantity)
VALUES(#ProductID,#LocationID,#quantity)";
command = new SqlCommand(commandText, this.CurrentConnection);
command.CommandType = CommandType.Text;
command.Transaction = sqlTransaction;
SqlParameterCollection paramCols = command.Parameters;
//this loop will do the update or insert for all rows in the table
// How can we optimize to only ONE CALL to database?
foreach (DataRow row in table.Rows)
{
paramCols.Clear();
paramCols.AddWithValue("#ProductID",row["ProductID"]);
paramCols.AddWithValue("#LocationID", row["LocationID"]);
paramCols.AddWithValue("#Quantity", row["Quantity"]);
result &= command.ExecuteNonQuery()>= 0;
}
return result;
}
catch
{
throw;
}
}
**My question is how we can optimize the code so only one call to ExecuteNonQuery to update the database instead of having it in a loop? Please note that we are not using StoredProcedure and all should be from C# and SQL Queries or Transactions.
if it was just Update the rows, we could call command.Update with providing the source table and it easily update all the rows without using rows. but since i am using 'IF Exists' then we are forced to use ExecuteNonQuery which is not accepting source table as parameter.
Thank You
Instead of using a ParameterCollection you could do:
command.Parameters.Add(new SqlParameter("#ProductID", ProductData.PRODUCTID_FIELD));
or
command.Parameters.AddWithValue("#ProductID", ProductData.PRODUCTID_FIELD);
and so on. You don't actually have to specify the type.
Then call:
int numOfRowsAffected = command.ExecuteNonQuery();
There is no dataset to be returned, only the number of rows affected, since this is a non-query.
The problem with making a ParameterCollection like you are doing is you then need to set command.Parameters = paramCols; but command.Parameters is Read-Only, so you can't. That is, its read-only as far as assignment goes. You can only add parameters to it through the methods Add and AddWithValue.
for multiple rows , add command in loop
foreach (DataRow row in table.Rows)
{
SqlCommand command = new SqlCommand();
.
.
.
}
I want to check to see if some of the fields have some unique values - for instance, I want to check if field1, field2 in my table have a value of "YES". If both of them have "Yes" then I want to call some function, but if one of them has "No" value then I want to call some other function. Note in my select statement, I am passing an ID from the query-string. How can I do this?
protected void Check_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e) {
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT ID, Field1, Field2 from MyTabel WHERE ID = '" + Request.QueryString["ID"] + "'", con);
DataTable dt = new DataTable();
da.Fill(dt);
}
If figuring out whether a specific set of criteria exists or not in a given record is all you need, then I can suggest you doing this check on Database side and then using ExecuteScalar to get the result:
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
{
using(SqlCommand cmd = new SqlCommand("SELECT count(*) from MyTabel WHERE ID =#ID And (Field1='Yes' And Field2='Yes')" , con))
{
cmd.parameters.Add("#ID",Request.QueryString["ID"]);
con.open();
int result = cmd.ExecuteScalar();
con.close();
if(result == 1)
// condition exists
// so call success function
else
// call failure function
}
}
Update:
This may not be directly related to the question but to get record Id from detailsView, you need to go through 2 steps:
Set the datakeynames property for the detailsView to the name of your table's primary key name – in this case, ID.
<asp:detailsview datakeynames="ID"
Now you can access the selected Id by
int id = (int)detailsView.SelectedValue;
Check here for more information.