mercredi 1 avril 2015

How to UPDATE multiple columns using a correlated subquery in SQLite?

I want to update multiple columns in a table using a correlated subquery. Updating a single column is straightforward:



UPDATE route
SET temperature = (SELECT amb_temp.temperature
FROM amb_temp.temperature
WHERE amb_temp.location = route.location)


However, I'd like to update several columns of the route table. As the subquery is much more complex in reality (JOIN with a nested subquery using SpatiaLite functions), I want to avoid repeating it like this:



UPDATE route
SET
temperature = (SELECT amb_temp.temperature
FROM amb_temp.temperature
WHERE amb_temp.location = route.location),
error = (SELECT amb_temp.error
FROM amb_temp.temperature
WHERE amb_temp.location = route.location),


Ideally, SQLite would let me do something like this:



UPDATE route
SET (temperature, error) = (SELECT amb_temp.temperature, amb_temp.error
FROM amb_temp.temperature
WHERE amb_temp.location = route.location)


Alas, that is not possible. Can this be solved in another way?


Here's what I've been considering so far:



  • use INSERT OR REPLACE as proposed in this answer. It seems it's not possible to refer to the route table in the subquery.

  • prepend the UPDATE query with a WITH clause, but I don't think that is useful in this case.


i want commercial open source database software

i have Sql lite, but that is not working properly. please suggest me anything else that u know. I have data of 35000 records. i want to work on that data using Sql. I was working on Sql lite,but data couldn't get update. when i tried to update data suddenly Sql lite stops working. i want next option other than Sql lite. but the thing is that that option should be Commercial open source database software. i have Sql lite, but that is not working properly. please suggest me anything else that u know. I have data of 35000 records. i want to work on that data using Sql. I was working on Sql lite,but data couldn't get update. when i tried to update data suddenly Sql lite stops working. i want next option other than Sql lite. but the thing is that that option should be Commercial open source database software.


In C# How to read data from table and after some calculation save those data in another table?

I an new in C#.I am trying to read data from a table named 'tblAddResult'. In this table I have some columns and i want to make average of 3 columns of tblAddResult and save it to a new table named tblResult. SOme other calculations also wanna do there like Taking 50% of a data of a column of tblAddResult.I did this in this way(code placed below) but i am getting an error "invalid attempt to call read when reader is closed". I dont even know is this the right way to do it if not can anyone help me with the write way or any suggestions regarding this way. I am really helpless for this problem.



private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("SELECT tblAddResult.* FROM tblAddResult", con);
SqlDataReader sdr = cmd.ExecuteReader();

while (sdr.Read())
{

String subject = sdr.GetString(2);
int january = sdr.GetInt32(3);
int february = sdr.GetInt32(4);
int march = sdr.GetInt32(5);
int average = (january + february + march) / 3;
int average40= average*40/(100);
int marks = sdr.GetInt32(6);
int marks50 = marks * 50 / 100;
int WorkingDay = sdr.GetInt32(7);
int Attandence = sdr.GetInt32(8);
int Attendence10 = Attandence * 10 / 100;
int totalMarks = average40 + marks50 + Attendence10;
string grade = "" ;
if (totalMarks < 51) { grade = "C"; }
else if (totalMarks < 61) { grade = "B"; }
else if (totalMarks < 71) { grade = "A-"; }
else if (totalMarks < 81) { grade = "A"; }
else if (totalMarks < 91) { grade = "A+"; }
else if (totalMarks <= 100) { grade = "A++"; }
con.Close();
con.Open();
SqlCommand comnd = new SqlCommand("INSERT INTO tblResult (Subject, [Full Marks], January, February, March, [Average Class Perfomance], [Earned Marks], [Working Day], Attendence, [Cls Attendence(40%)], [Exam Perfomance(50%)], [Attendence(10%)], [Marks(%)], Grade)VALUES ('"+subject+"','"+"100"+"','"+january+"','"+february+"','"+march+"','"+average+"','"+marks+"','"+WorkingDay+"','"+Attandence+"','"+average40+"','"+marks50+"','"+Attendence10+"','"+totalMarks+"','"+grade+"')",con);
comnd.ExecuteNonQuery();
MessageBox.Show("Successfull!");

}

query in sqlite about second row

i have the following query to get the second row in studentsubject table it's work well but I need another way give better performance than using subquery



select SbID , StID, max(mark)
from studentsubject
where mark <( select max(mark) from studentsubject)
group by SbID
order by mark desc
limit 5

displaying sqlite records return error

I have this code for displaying records from sqlite.



class MyDB extends SQLite3
{
function __construct()
{
$this->open('database.sqlite');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}


$sql =<<<EOF
SELECT * from database_table_column;
EOF;

$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "database id = ". $row['id'] . "\n";
echo "database name = ". $row['database_name'] ."\n";
echo "column name = ". $row['column_name'] ."\n";
}
echo "Operation done successfully\n";
$db->close();


and I got this following error (refer below) 1. Warning: SQLite3::query(): Unable to prepare statement: 1, no such table: database_table_column 2. Fatal error: Call to a member function fetchArray() on a non-object


I'm sure I have database.sqlite file and created a database_table_column table with id column, database_name column and column_name column but why doesnt work? any ideas, suggestions, recommendations and help would be greatly appreciated. Thank you.


Android clear listview linked to SQLite

I have the following activity populating listview from SQLite. When click on empty I delete table content correctly and refresh the CartActivity which appears empty. If I add new element in my cart then old elements appears again but only in the listview and (correctly) not in my db. If I close the application the listview update itself correctly.


Tried to give a look at similar question, tried with notify but nothing happens. Someone wrote about "you delete the data but not the entries" but I'm not able to.


How could I solve this issue?


Any help would be much appreciated. Thanks in advance.



public class CartActivity extends Activity {
ListView list;
Context context;
SessionManagement session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
Typeface font = Typeface.createFromAsset(this.getAssets(), "font/VarelaRound-Regular.ttf");
context = getApplicationContext();
session = new SessionManagement(context);
final CartHandler db = new CartHandler(this);
Log.d("Reading: ", "Reading all contacts..");
final List<CartRow> products = db.getAllProducts();

for (CartRow cn : products) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Number: " + cn.getNumber() + " ,Pieces: " + cn.getPieces() + " ,Price: " + cn.getPrice() + " ,Tot: " + cn.getTotPrice();
Log.d("Nome: ", log);
}
if(products.isEmpty() ){
//Intent intent = new Intent(getApplicationContext(),MenuActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//startActivity(intent);
Toast.makeText(this, "", Toast.LENGTH_LONG).show();
//finish();
} else {
final CartHandler mdb = new CartHandler(this);
getItemsFromDatabase(mdb);
final CustomCarterList adapter = new CustomCarterList(CartActivity.this);
list = (ListView) findViewById(R.id.cart);
list.setAdapter(adapter);
Button empty = (Button) findViewById(R.id.emptycart);
empty.setTypeface(font);
empty.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
db.deleteAll();
//mdb.deleteAll();
Intent intent = new Intent(CartActivity.this, CartActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
Button proceed = (Button) findViewById(R.id.proceed);
proceed.setTypeface(font);
proceed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!session.isLoggedIn()) {
Intent intent = new Intent(CartActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(
getApplicationContext(),
CheckoutActivity.class
);
startActivity(intent);
}
}
});

}

}

public void getItemsFromDatabase(CartHandler mdb) {
Cursor cursor = null;
try{
SQLiteDatabase db =mdb.getReadableDatabase();
cursor=db.rawQuery("select * from products", null);
while (cursor.moveToNext()){
Log.e("Cart", cursor.getString(1)+":"+cursor.getString(2)+":"+cursor.getString(3)+":"+cursor.getString(4)+":"+cursor.getString(5));
CartRow.itemIdList.add(cursor.getString(0));
CartRow.itemNameList.add(cursor.getString(1));
CartRow.itemQuantityList.add(cursor.getString(2));
if (cursor.getString(3).equals("0")){
CartRow.itemPiecesList.add("Pieces: 1");}
else{
CartRow.itemPiecesList.add("Pieces: "+cursor.getString(3));}
CartRow.itemPriceList.add(cursor.getString(4) + ".00€");
CartRow.itemTotPriceList.add(cursor.getString(5)+".00€");
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}

mardi 31 mars 2015

Add and Retrieve data from SQLite Database Android in listview

Ok so i'm new here and i know this question has been asked many times but i cant seem to get anything to work i can get some samples i've found to work fine in a listview but if i try to modify or recreate i just cant seem to get it to work so im curreouse as to what i am doing wrong my code....sorry in advance for the bad formatting.



public class OrgEventCreationActivity extends Activity {

private SQLiteAdapter mySQLiteAdapter;
public EditText eventnames;
public EditText evedes;
public EditText numofv;
public EditText possisions;
public EditText skills;
public EditText minage;
public Button saveevent;
public Button proceed;
public Button stime;
public Button etime;
public Button date;
public ListView list;
public Button submit;

/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_org_event_creation);

eventnames = (EditText)findViewById(R.id.eventnameinput);
evedes = (EditText)findViewById (R.id.eventdescriptioninput);
numofv = (EditText)findViewById (R.id.numofv);
possisions = (EditText)findViewById (R.id.posinput);
skills = (EditText)findViewById (R.id.skillsinput);
minage = (EditText)findViewById (R.id.minage);
saveevent =(Button)findViewById (R.id.aeventbtn);
proceed = (Button)findViewById (R.id.submitbtn);
stime = (Button)findViewById (R.id.stimebtn);
etime = (Button)findViewById (R.id.etimebtn);
date = (Button)findViewById (R.id.datepicker);
list = (ListView)findViewById (R.id.orglist);
submit = (Button)findViewById (R.id.submitbtn);
submit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent us = new Intent (OrgEventCreationActivity.this,UserHomeActivity.class);
startActivity(us);
}
});

saveevent.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
populatelist();
}
});

}
public void populatelist(){

String evename = eventnames.getText().toString().trim();

/*
* Create/Open a SQLite database
* and fill with dummy content
* and close it
*/

mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.deleteAll();

mySQLiteAdapter.insert(evename);


mySQLiteAdapter.close();

Intent log = new Intent(OrgEventCreationActivity.this, UserHomeActivity.class);
startActivity(log);


}


mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();

Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);

String[] from = new String[]{SQLiteAdapter.MYDATABASE_TABLE};
int[] to = new int[]{R.id.text};

SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);

listContent.setAdapter(cursorAdapter);

mySQLiteAdapter.close();


}
}
}


the activity to display listview



import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class UserHomeActivity extends Activity {

private SQLiteAdapter mySQLiteAdapter;

/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listContent = (ListView)findViewById(R.id.contentlist);

/*
* Create/Open a SQLite database
* and fill with dummy content
* and close it
*
* mySQLiteAdapter = new SQLiteAdapter(this);
*mySQLiteAdapter.openToWrite();
* mySQLiteAdapter.deleteAll();

*mySQLiteAdapter.insert("Charity Dinner");
*mySQLiteAdapter.insert("Fundraiser");
*mySQLiteAdapter.insert("Benifit Concert");
*mySQLiteAdapter.insert("Silent Auction");
*

*mySQLiteAdapter.close();
*/
/*
* Open the same SQLite database
* and read all it's content.
*/
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();

Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);

String[] from = new String[]{SQLiteAdapter.MYDATABASE_TABLE};
int[] to = new int[]{R.id.text};

SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);

listContent.setAdapter(cursorAdapter);

mySQLiteAdapter.close();


}
}


and this is my database



import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.view.View.OnClickListener;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class SQLiteAdapter {

public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String NAME_COLUMN = "EVENTS";
public static final String KEY_ID = "_id";

public static final String KEY_CONTENT = "events";

//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key aautoincrement,"+ "evnents text);";

private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;

private Context context;

public SQLiteAdapter(Context c){
context = c;
}



public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}

public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}

public void close(){
sqLiteHelper.close();
}

public void insertEntry(String evename)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("EVETS",evename);


// Insert the row into your table
sqLiteDatabase.insert("ev", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}





public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}

public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
NAME_COLUMN, null, null, null, null);

return cursor;
}

public class SQLiteHelper extends SQLiteOpenHelper {

public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}

}

}


i've been trying to figure this out for days now if you can help i would be truly greatful