Connect to MSSQL with USB in android - android

private void fillCustomerInformationFields() throws SQLException {
Connection conn = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet;
Intent intent = getIntent();
String IDValue = intent.getStringExtra("id");
String query = "SELECT SiparisID, M.MusteriAdi + ' ' + M.MusteriSoyadi AS MusteriAdi, U.UrunAdi," +
" CASE WHEN OdemeTuru=0 THEN ? WHEN OdemeTuru=1 THEN ? WHEN OdemeTuru=2 THEN ? END AS OdemeTuru, TeslimTarihi,"+
"M.musteriAdresi, SiparisDurumu, Aciklama FROM Siparisler S INNER JOIN Musteriler M ON M.MusteriID=S.MusteriID INNER JOIN Urunler U ON U.UrunID=S.urunID"+
"WHERE S.SiparisID='"+IDValue+"'";
try {
conn = getDBConnection();
preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,"Peşin");
preparedStatement.setString(2,"Taksitli");
preparedStatement.setString(3,"Kapıda");
resultSet = preparedStatement.executeQuery();
while(resultSet.next())
{
edtSiparisID.setText(resultSet.getString("SiparisID"));
edtUrunAdi.setText(resultSet.getString("UrunAdi"));
edtMusteriAdi.setText(resultSet.getString("MusteriAdi"));
edtOdemeTuru.setText(resultSet.getString("OdemeTuru"));
edtTeslimTarihi.setText(resultSet.getString("TeslimTarihi"));
edtSiparisAdresi.setText(resultSet.getString("musteriAdresi"));
edtAciklama.setText(resultSet.getString("Aciklama"));
}
}catch (SQLException e){
e.printStackTrace();
}finally {
if(preparedStatement != null){
preparedStatement.close();
}
if(conn != null){
conn.close();
}
}
}
Hello everyone. İ'm making a project and i connect to mssql from android app via usb. I wrote to code for read data from mssql but i'm getting error. how can i fix the error? Thanks for the help
The exception displayed in LogCat is:
com.example.uur.stock W/System.err﹕ java.sql.SQLException: Incorrect syntax near 'S'.

Check your query
String query = "SELECT SiparisID, M.MusteriAdi + ' ' + M.MusteriSoyadi AS MusteriAdi, U.UrunAdi," +
" CASE WHEN OdemeTuru=0 THEN ? WHEN OdemeTuru=1 THEN ? WHEN OdemeTuru=2 THEN ? END AS OdemeTuru, TeslimTarihi,"+
"M.musteriAdresi, SiparisDurumu, Aciklama FROM Siparisler S INNER JOIN Musteriler M ON M.MusteriID=S.MusteriID INNER JOIN Urunler U ON U.UrunID=S.urunID"+
"WHERE S.SiparisID='"+IDValue+"'";
this is causing the exception:
FROM Siparisler S JOIN Musteriler M
must change to
FROM Siparisler as S JOIN Musteriler as M
More info:
SQLite - ALIAS Syntax

Related

SQLite SELECT MAX() query returns null to cursor?

I have a SQLite Table called "TBL_EVO" where I want to get the biggest value from column "DATE_MODIFIED". With following query I got the result in SQLite Browser like below.
SELECT MAX(DATE_MODIFIED) FROM 'TBL_EVO';
When I run the query from code from my application I got a nullpointerexception. Database is absolutly the same like in the SQLBrowser.
So DATE_MODIFIED exists with its values.
It crashes at cursor.moveToFirst();.
Even when I surround it with if(cursor.moveToFirst())
When I do this the code jumps to else.
What am I doing wrong?
MainActivity.java
MySQLiteHelper db = new MySQLiteHelper(this);
String strDateTime = db.strSelectMaxDate(TableNames[intTableIDStart]);
Log.v("TBL_EVO_DATE_TIME: ", "-> "+strDateTime);
MySQLiteHelper.java - strSelectMaxDate
public String strSelectMaxDate(String strTable){
String strValueFromDB = "";
String queryMaxDate = "SELECT MAX(DATE_MODIFIED) FROM '" + strTable+"'";
Log.v("TBL_EVO_DATE_TIME_QUERY", queryMaxDate);
try{
db = this.getReadableDatabase();
cursor = db.rawQuery(queryMaxDate, null);
cursor.moveToFirst();
if(cursor == null){
strValueFromDB = "cursorisnull";
Log.v("TBL_EVO_DATE_TIME_VAL1", strValueFromDB);
}else {
strValueFromDB = cursor.getString(0);
Log.v("TBL_EVO_DATE_TIME_VAL2", cursor.getString(0));
}
}catch(Exception e){
Log.v("TBL_EVO_DATE_TIME_ERROR", "-> "+e);
strValueFromDB = "error: "+e;
}finally{
cursor.close();
db.close();
}
return strValueFromDB;
}
Logcat
09-24 15:24:23.207 21900-21917/com.spicysoftware.goexpert V/TBL_EVO_DATE_TIME_QUERY: SELECT MAX(DATE_MODIFIED) FROM 'TBL_EVO'
09-24 15:24:23.216 21900-21917/com.spicysoftware.goexpert V/TBL_EVO_DATE_TIME_ERROR: -> java.lang.NullPointerException: println needs a message
09-24 15:24:23.216 21900-21917/com.spicysoftware.goexpert V/TBL_EVO_DATE_TIME:: -> error: java.lang.NullPointerException: println needs a message
Replace your queryMaxDate with:
String queryMaxDate = "SELECT MAX(DATE_MODIFIED) FROM " + strTable;
I solved the problem.
Problem was, that I did a new SQLConnection in an asynctask.
I had to open a new connection in Asynctask.

Android to MS Sql query

my application was working fine but then i changed something and its not inserting records in the database. when ever i press the submit button it show me toast "Record not inserted"
here is the code
connect=connn.ConnHelper(username, password, db, ipaddress);
if (connect == null){
Toast.makeText(getBaseContext(),"Connection Unsuccessfull",Toast.LENGTH_LONG).show();
}
else {
//inserting records in database
//is se nechy nechy
try {
st = connect.createStatement();
String query = "insert into profiles(Name,City,Address,Speciality,Phone,CNIC,Picture,Status) values('" + name + "','" + city + "','" + add + "','"+spec+"','"+ph+"','"+cn+"','"+img+"','pending');";
preStatement = connect.prepareStatement(query);
int k=preStatement.executeUpdate();
if(k==1){
Toast.makeText(getBaseContext(),"Record Inserted Successfully",Toast.LENGTH_LONG).show();
Intent imageIntent = new Intent("com.androsoft.application.Profile");
imageIntent.putExtra("Id",Cnic.getText().toString());
startActivity(imageIntent);
}
else{
Toast.makeText(getBaseContext(),"Record Not Inserted",Toast.LENGTH_LONG).show();
}
} catch (SQLException e) {
Toast.makeText(getBaseContext(),"Record Not Inserted",Toast.LENGTH_LONG).show();
}
here its returning zero to k.
mydatabase entities are.
database entities
Try to run this application in debug mode, and get the String query value on runtime (like insert into profiles(Name,City,Address,Speciality,Phone,CNIC,Picture,Status) value('dav','city','new york',null,'33','f');, then try to execute the query directly in sql server. If there is no problem in your query so this is something in the connection to the data base or problem in the application.

Error on using REPLACE character manipulation function on query SQLite Android

it gives me an error when I am using this key but when I use LENGTH, it works fine. I hope it is allowed on android sqlite coz it's the best way for this:
I am just trying to remove the spaces after words that will be selected from Database.
public ArrayList<String> getCorrectList() {
// TODO Auto-generated method stub
Cursor c = db.rawQuery("SELECT REPLACE(Level_1, ' ', '') FROM " + TABLE, null);
ArrayList<String> resultsList = new ArrayList<String>();
try {
if (c != null) {
if (c.moveToFirst()) {
do {
String levelData = c.getString(c
.getColumnIndex("Level_1"));
resultsList.add("" + c.getColumnIndex("Level_1"));
} while (c.moveToNext());
}
}
} catch (SQLiteException e) {
Log.e("Database", "Cannot get List (" + e + ")");
}
Log.d("array", "List: " + resultsList);
Collections.shuffle(resultsList);
return resultsList;
}
This works fine in SQLite3 shell:
e$ sqlite3
SQLite version 3.7.14.1 2012-10-04 19:37:12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table t(a,b,c);
sqlite> select replace(a,' ', '') from t;
REPLACE is both a function and a command in SQLite3. Perhaps db.rawQuery is parsing the query and getting confused by REPLACE. Try this:
db.rawQuery("select rtrim(replace(Level_1, ' ', '')) FROM " + TABLE, null);

Android : SQLiteException: not an error not on all devices

I get this error on a device, while it works good on another device. Here is the error :
Caused by: android.database.sqlite.SQLiteException: not an error
at android.database.sqlite.SQLiteQuery.nativeFillWindow(Native Method)
at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:86)
at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:164)
at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:156)
at com.Orange.MakeVisits.Themes.onCreate(Themes.java:162)
I execute a query and at the line that checks if the Cursor is null, I get this error. Here is my code :
String stmtGetThemes = "SELECT * FROM pr_fields_descriptor a "
+ "inner join pr_fields_starring b on a.id_fields_descriptor = b.fields_descriptor_id "
+ "where b.starring_id = '"+pos_starring_id+"' and a.theme_id='"+themes_ids[m]+"' order by form_rank";
Cursor getThemesCursor1 = db.databaseQuery(stmtGetThemes);
if (getThemesCursor1!=null && getThemesCursor1.getCount()>0){
//----
}
and databasequery is this method (is defined in the class that extends SQLiteOpenHelper):
public Cursor databaseQuery(String stmt) {
Cursor cursor = db.rawQuery(stmt, null);
return cursor;
}
Any idea what can cause this error ? The statement is not good ? Why it works on others devices?
Any idea is welcome. Thanks in advace.
String stmtGetThemes = "SELECT * FROM pr_fields_descriptor a "
+ "inner join pr_fields_starring b on a.id_fields_descriptor = b.fields_descriptor_id "
+ "where b.starring_id = '"+pos_starring_id+"' and a.theme_id='"+themes_ids[m]+"' order by form_rank";
Do not terminate this query by ";".
Don't Pass array Type Paramters in Query, sometimes it won't work
int themes_id = themes_ids[m];
String stmtGetThemes = "SELECT * FROM pr_fields_descriptor a inner join pr_fields_starring b on a.id_fields_descriptor = b.fields_descriptor_id where b.starring_id = '"+pos_starring_id+"' AND a.theme_id = '"+themes_id+"' ORDER BY form_rank";
Cursor getThemesCursor1 = db.databaseQuery(stmtGetThemes);
if (getThemesCursor1 != null && getThemesCursor1.getCount() != 0){
//----
}

Android - SQLiteStatement (multiple insert) execute fails with API Level 14

I use the following code to insert new lines efficiently in a DB :
#Override
public void insertImpacts(HolderExpense expense, int[] shares, int[] amounts, HolderUser[] users) {
try {
mDb.beginTransaction(); // the insertion of the impacts of one expense are considered to be ONE block
String sql = "INSERT INTO "+DATABASE_TABLE_IMPACTS+" "+
"("+IMPACT_USERROWID+", "+IMPACT_EXPENSEROWID+", "+IMPACT_TTROWID+", "+IMPACT_NUMBEROFPARTS+", "+IMPACT_FIXEDAMOUNT+") VALUES (?, ?, ?, ?, ?)";
SQLiteStatement stmt = mDb.compileStatement(sql);
stmt.bindLong(2, expense.rowId);
stmt.bindLong(3, expense.tt.rowId);
int i = 0;
while (i < shares.length) {
if (users[i] != null) {
Log.v(TAG, "user " +i+": users[i].rowId:"+users[i].rowId+" expense.rowId:"+expense.rowId+" expense.tt.rowId:"+expense.tt.rowId+" shares[i]:"+shares[i]+" amounts[i]:"+amounts[i]+" ");
stmt.bindLong(1, users[i].rowId);
stmt.bindString(4, shares[i]+"");
stmt.bindString(5, amounts[i]+"");
stmt.execute();
}
i++;
}
stmt.close();
mDb.setTransactionSuccessful();
}
catch (Exception e) { e.printStackTrace(); throw new RuntimeException("insertImpacts() failed"); }
finally { mDb.endTransaction(); }
}
It works until android 4.x where I get that error:
02-26 14:27:46.179: W/System.err(937): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
02-26 14:27:46.179: W/System.err(937): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
02-26 14:27:46.219: W/System.err(937): at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:92)
02-26 14:27:46.219: W/System.err(937): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:70)
Seems it crashes at stmt.execute() when inserting the second line into the table.
Any clue ?
-- EDITION --
The schema of the table is the following:
private static final String DATABASE_CREATE_TABLE_IMPACTS =
"create table " + DATABASE_TABLE_IMPACTS + " ("
+ IMPACT_ROWID + " integer primary key autoincrement, "
+ IMPACT_USERROWID + " integer not null, "
+ IMPACT_EXPENSEROWID + " integer not null, "
+ IMPACT_TTROWID + " integer not null, "
+ IMPACT_NUMBEROFPARTS + " integer not null, "
+ IMPACT_FIXEDAMOUNT + " integer not null, "
+ "constraint i_cstr1 unique ("+IMPACT_USERROWID+", "+IMPACT_EXPENSEROWID+")); ";
This code works like a charm on Android 2.2 (but fails on Android 4.0).
Print of the two first lines I insert (it crashes when trying to insert the second):
02-26 14:27:46.069: E/DatabaseAdapter.java(937): user 0: users[i].rowId:7 expense.rowId:2 expense.tt.rowId:2 shares[i]:1 amounts[i]:-1
02-26 14:27:46.069: E/DatabaseAdapter.java(937): user 1: users[i].rowId:5 expense.rowId:2 expense.tt.rowId:2 shares[i]:1 amounts[i]:-1
Found. The different version of android do not behave the same way. On Android 4.x, all the 'bindXXX' lines must be placed in the 'while' loop. Even if it is repetitive.
while (i < shares.length) {
if (users[i] != null) {
stmt.bindLong(1, users[i].rowId);
stmt.bindLong(2, expense.rowId);
stmt.bindLong(3, expense.tt.rowId);
stmt.bindString(4, String.valueOf(shares[i]));
stmt.bindString(5, String.valueOf(amounts[i]));
stmt.execute();
}
i++;
}
This is perfect Gilbou! I also made your data binding solution for my task: csv file importing to SQLite database. There was about 25.000 rows in the csv file, and importing it and insert to SQLite takes for me about 5 seconds (before it took 5 minutes without data binding!!)
Thank you so so much!
I also share mine, maybe it can helps for somebody, too (Android 4.0):
public boolean updateFromCsv() {
boolean ok = true;
String line = "";
BufferedReader br = null;
try {
FileInputStream fis = new FileInputStream(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Servantes/Be/leltariv_export.csv");
br = new BufferedReader(new InputStreamReader(fis));
} catch (FileNotFoundException e) {
ok = false;
e.printStackTrace();
}
try {
database.beginTransaction();
String sql = "INSERT INTO "+LeltarTable.TABLE_LELTAR_NEV+" "+
"("+LeltarTable.COLUMN_ID+", "+LeltarTable.COLUMN_LSZ+", "+LeltarTable.COLUMN_MEGN+", "+LeltarTable.COLUMN_HELY+", "+LeltarTable.COLUMN_DARAB+") VALUES (?, ?, ?, ?, 0)";
SQLiteStatement stmt = database.compileStatement(sql);
while ((line = br.readLine()) != null) {
String[] colums = line.split(";");
stmt.bindAllArgsAsStrings(colums);
stmt.execute();
}
stmt.close();
database.setTransactionSuccessful();
}catch (Exception e) {
e.printStackTrace();
ok = false;
}
finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
ok = false;
}
database.endTransaction();
}
return ok;
}

Categories

Resources