I have four columns in an sqlite table and I want to delete data of three columns and keep the data of other one - sqlite

I have four columns in a table. I am using sqlite database and I want to delete data of three columns and keep the data of other one column.
String sql="DELETE january,deducted,remaining FROM sailary where id=?";
try
{
pst = conn.prepareStatement (sql);
pst.setString (1, jut.getText());
pst.execute();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}

delete is used to remove rows. What you could do is update these columns to be null in the specific row you're referring to:
UPDATE sailary
SET january = NULL, deducted = NULL, remaining = NULL
WHERE id = ?

Related

get all data from dynamo db table without supplying any PK

I am trying to fetch all the data from my dynamodb table but unable to get as all the methods for Query / Scan operates with input parameter. so i tried getting all the rows which having primary key greater than 0.
var table = Table.LoadTable(client,Utilities.Utility.EmployeeTable);
ScanFilter filter = new ScanFilter();
filter.AddCondition("iemp_id", ScanOperator.GreaterThan, 0);
ScanOperationConfig config = new ScanOperationConfig()
{
Filter = filter,
// Optional parameters.
Select = SelectValues.SpecificAttributes,
AttributesToGet = new List<string> { "iemp_id", "demp_salary", "semp_name" }
//ConsistentRead = true
};
Search search = table.Scan(config);`
Here i am getting search.Matches = 0 where it should return data from my table.
You have only two options
1.Query : You need to supply Partition Key(mandatory) and optionally Range key.
2.Scan: Full scan of the table with out Partition key/Range Key.
In your case you will have to do full scan of the table.
DynamoDBQScanExpression scanExpression = new DynamoDBScanExpression();
scanExpression .withFilterExpression(filterexpression)
.withExpressionAttributeValues(expression values);

Transactions with Prepared Statements fails

I try to use transactions with prepared statementsin order to update table INVENTORY where :
CREATE TABLE "INVENTORY" (
"product" VARCHAR NOT NULL,
"version" VARCHAR NOT NULL,
"lot" VARCHAR,
"barcode" VARCHAR,
"quantity" INTEGER,
PRIMARY KEY ("barcode")
);
What I want to do is to insert a new row, but if in my table a row exists with the same primary key then to update it by adding the old value + the new.
I read this and this and I think I followed the instructions right.
String sqInsert = "INSERT INTO INVENTORY VALUES ('100541026044','01','301610101','10054102604401301610101','5000')";
String sqUpdate = "UPDATE INVENTORY set quantity = quantity + 5000 where barcode='10054102604401301610101'";
// transaction block start
c.setAutoCommit(false);
stm = c.prepareStatement(sqInsert);
System.out.println("try to insert");
result = stm.executeUpdate();
System.out.println("try to update");
stm = c.prepareStatement(sqUpdate);
result = stm.executeUpdate();
c.commit(); //transaction block end
System.out.println("Done!");
In my table a row with barcode=10054102604401301610101 exists, so I want the update to be executed. However, I get
try to insert
Error inserting products :[SQLITE_CONSTRAINT] Abort due to constraint violation (UNIQUE constraint failed: INVENTORY.barcode)
Note: (I don't set the values from query, but with stm.setString(1, "string");) I just want to be short the code here
Of course it will fail due to a duplicated primary key on the bar code.
First do the update
stm = c.prepareStatement(sqUpdate);
result = stm.executeUpdate();
Then check the value of result which will be the number of rows affected by the update. If it is zero then the product with given barcode didn't exist so after the update do
if (0==result) {
stm = c.prepareStatement(sqInsert);
stm.executeUpdate();
}
You'll want to put everything under a try {} catch {} to avoid a resource leak or leaving the connection unusable
try {
c.setAutoCommit(false);
stm = c.prepareStatement(sqUpdate);
result = stm.executeUpdate();
if (0==result) {
stm.close();
stm = null;
stm = c.prepareStatement(sqInsert);
stm.executeUpdate();
stm.close();
stm = null;
}
c.commit();
} catch (SQLException e) {
if (stm!=null) stm.close();
c.rollback();
}

Insert the newset value in a table and drop the old ones

I have a method which saves somes records for a machine in a table. However, I may insert by accident multiple times the records for the same machine in a day, so I want for this day to save the newest insert and drop the old ones. I thought one solution:
String sq = "SELECT date, idMachine "
+ "FROM MACHINES_RECORDS WHERE date = ? AND idMachine = ?";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
ResultSet rs = stm.executeQuery();
if (rs.next()) {
do {
//call an another method to drop this value
} while(rs.next());
}else {
//call an another method to insert this value
}
}catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (stm != null)
stm.close();
if (c != null)
c.close();
}
Is there any better/smartest solution from this, so I can make all theses actions in the same method?
With a unique index (possibly the primary key) on date and idmachine you would use INSERT ... ON DUPLICATE KEY UPDATE, so as to insert when there is no entry for that machine on that day or update the existing record with the new data otherwise.
insert into machines_records
(machineid, date, data)
values
(#id, #date, #data)
on duplicate key update data = #data;
EDIT: I see you removed the MySQL tag. So you want an answer for SQLite. In SQLite you'd use INSERT OR REPLACE:
insert or replace into machines_records
(machineid, date, data)
values
(#id, #date, #data);

How To Convert rows into Column in SQL?

Actually I have query which returns me 5 columns and values(date) for each or them in a single row but what I want is the columns names should be in a single column Title and its (Vale) in second columns in Date.
Note Title and Date are the columns of the temporary table I just created run time.
Here is my piece of code I am using,
protected void btnAlerts_Click(object sender, EventArgs e)
{
fnSaveAlerts();
}
private void fnSaveAlerts()
{
DataTable dtTemp = new DataTable();
DataColumn dtC1 = new DataColumn();
dtC1.DataType = typeof(String);
dtC1.ColumnName = "Title";
DataColumn dtc2 = new DataColumn();
dtc2.DataType = typeof(DateTime);
dtC1.ColumnName = "Date";
dtTemp.Columns.Add(dtC1);
dtTemp.Columns.Add(dtc2);
LeadsContracts ObjLeadsContract = new LeadsContracts();
ObjLeadsContract.ExecuteSql(#"select dtDisclosure, dtDueDiligence,
dtFinanceAppraisals, dtFreeTextDate1,
dtFreeTextDate2
from LeadsContracts
where dtDisclosure is not null
and dtDueDiligence is not null
and dtFinanceAppraisals is not null
and dtFreeTextDate1 is not null
and dtFreeTextDate2 is not null");
dtTemp.DataSet = ObjLeadsContract.DefaultView; // it also gives error here "Red line"
}
I have already spend whole day to do this, please any body can help me. thanks in advance
I'll give you hints for a solution:
For your problem you can use a two-dimenstional array.
[0]["Title", DatabaseValue]
[1]["Date", DatabaseValue]
[2][
[3][
[4][
So, first loop over the five values of your query and fill into the two dimensional array
[0][1]
[1][1]
[2][1]
[3][1]
[4][1]
Then you can loop over the two dimensional array for your output...
Are you expecting something like this?
DECLARE #Temp AS TABLE (dtDisclosure varchar(20),dtDueDiligence varchar(20),dtFinanceAppraisals varchar(20),dtFreeTextDate1 varchar(20),dtFreeTextDate2 varchar(20))
INSERT INTO #Temp VALUES ('20-Apr-2013','20-Apr-2013','20-Apr-2013','20-Apr-2013','20-Apr-2013'),
('21-Apr-2013','21-Apr-2013','21-Apr-2013','21-Apr-2013','21-Apr-2013')
SELECT [Title],[Date] FROM
(
SELECT * FROM #temp
} A
UNPIVOT
{
[Date] FOR [Title] IN IN ([dtDisclosure],[dtDueDiligence],[dtFinanceAppraisals],[dtFreeTextDate1],[dtFreeTextDate2])
} AS Unpvt;
OUTPUT :
Title Date
dtDisclosure 20-Apr-2013
dtDueDiligence 20-Apr-2013
dtFinanceAppraisals 20-Apr-2013
dtFreeTextDate1 20-Apr-2013
dtFreeTextDate2 20-Apr-2013
dtDisclosure 21-Apr-2013
dtDueDiligence 21-Apr-2013
dtFinanceAppraisals 21-Apr-2013
dtFreeTextDate1 21-Apr-2013
dtFreeTextDate2 21-Apr-2013

Edit the code of a GridView column asp.net

I've been looking for a way to control the text that appears in a particular column of a GridView.
For example consider a database with two tables Student and Class.
I want to add a column to the GridView which print out all the students in the Database, the column will show the student's class name, how can do it? (I can normally print the ClassId since its a FK in the student table)
I want to add a column to the GridView which print all the classes, the column will count the number of students in each class, how can I do it?
1- You can do that simply with inner join or a stored procedure to get the class name beside all the data you need in your query.
2- More than one way to do what you want:
For example:
you can add a column to your data table (empty column ), and fill it later through using Sum() aggregate function in a query.
DataTable result_dt = DAL_Helper.Return_DataTable(sqlSelect);//your original query
result_dt.Columns.Add("NumberOfStudent");
result_dt.Columns["NumberOfStudent"].DataType = typeof(string);
result_dt.Columns["NumberOfStudent"].MaxLength = 255;
if (result_dt.Rows.Count > 0)
{
for (int i = 0; i < result_dt.Rows.Count; i++)
{
//Here u can fill your new empty column.
}
}
result_dt.AcceptChanges();
After you return your customized data table(as a data source), you can bind it to the grid view.
Another solution : add an empty column to the grid view and in the RowDataBound event of the grid view you can fill this column through some loop and you can use LINQ to help you in getting the summation.

Resources