sqlite + java / java.sql.SQLException: no such column - java

I have a problem with querying a single column. Whereby it works when I query the whole table. Whats the problem?
I'm getting this error:
java.sql.SQLException: no such column: 'Id'
at org.sqlite.jdbc3.JDBC3ResultSet.findColumn(JDBC3ResultSet.java:54)
at org.sqlite.jdbc3.JDBC3ResultSet.getInt(JDBC3ResultSet.java:406)
at Application.DBStatement.showData(DBStatement.java:135)
at Application.DBStatement.createQuery(DBStatement.java:121)
at Application.DBStatement.search(DBStatement.java:179)
at Main.MainClass.main(MainClass.java:61)
//-----------------
try {
dbStatement.search(1, "");
} catch (Exception e) {
e.printStackTrace();
}
//------------------
public void search(int number, String searchText) throws SQLException {
String searchQuery= "";
switch (number) {
case 1:
searchQuery = "SELECT " + COLUMN_ID + " FROM " + TABLE_NAME + " WHERE " + COLUMN_Name + " = " + "'" + searchText + "'"; // that isn't working
//searchQuery = "SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_Name + " = " + "'" + searchText + "'"; // that's working
break;
default:
break;
}
}
//-----------------------
public void createTable() throws SQLException {
String createTable= "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
"( "
+ COLUMN_ID + " INTEGER PRIMARY KEY, "
+ COLUMN_Name + " TEXT NOT NULL, "
+ COLUMN_EMail + " TEXT NOT NULL, "
+ COLUMN_Registration_Date + " TEXT NOT NULL "
+ " )";
}

Related

Need to optimize the query to insert the record

I wrote a piece of JDBC template code, which inserts the record in the table, but the problem is my execution is stuck on this particular snippet, it seems some kind of hang up. I didn't figure out the cause as query properly running in sqldeveloper
List<SalaryDetailReport> reports = salaryDetailReportDAO.findAll(tableSuffix, regionId, circleId);
// the above line find the required data, if data is found then it proceeds
if (reports != null && reports.size() > 0) {
for (SalaryDetailReport salaryDetail : reports) {
try {
SalaryDetail sd = new SalaryDetail();
sd.setDetailReport(salaryDetail);
salaryDetailDAO.save(sd, tableSuffix);
} catch (Exception e) {
log.error("Error occured", e);
e.printStackTrace();
throw new MyExceptionHandler(" Error :" + e.getMessage());
}
}
System.out.println("data found");
} else {
log.error("Salary Record Not Found.");
throw new MyExceptionHandler("No record Found.");
}
You people saw try-catch , my execution stuck inside try and catch and here is the insertion code in my implementation class. when i commented the above code then my application works fine, but why my application stuck here, I am not able to figure it out, kindly help me
#Override
public void save(SalaryDetail details, String tableSuffix) {
String tabName = "SALARY_DETAIL_" + tableSuffix;
// String q = "INSERT INTO " + tabName + "(ID "
String q = "INSERT INTO SALARY_DETAIL_TBL "
+ " (ID "
+ " ,EMP_NAME "
+ " ,EMP_CODE "
+ " ,NET_SALARY "
+ " ,YYYYMM "
+ " ,PAY_CODE "
+ " ,EMP_ID "
+ " ,PAY_CODE_DESC "
+ " ,REMARK "
+ " ,PAY_MODE ) "
+ " (SELECT (sd.SALARY_REPORT_ID) ID "
+ " ,(sd.emp_name) emp_name "
+ " ,(sd.EMP_CODE) EMP_CODE "
+ " ,(sd.amount) NET_SALARY "
+ " ,(sd.YYYYMM) YYYYMM "
+ " ,(sd.pay_code) pay_code "
+ " ,(sd.emp_id) emp_id "
+ " ,(sd.PAY_CODE_DESC) PAY_CODE_DESC "
+ " ,(sd.REMARK) REMARK "
+ " ,(sd.PAY_MODE)PAY_MODE "
// + " FROM SALARY_DETAIL_REPORT_" + tableSuffix + " sd "
+ " FROM SALARY_DETAIL_REPORT_TBL sd "
+ " WHERE sd.PAY_CODE = 999 "
+ " AND sd.EMP_ID IS NOT NULL "
// + " AND sd.EMP_ID NOT IN (SELECT EMP_ID FROM SALARY_DETAIL_" + tableSuffix + ") "
+ " AND sd.EMP_ID NOT IN (SELECT EMP_ID FROM SALARY_DETAIL_TBL) "
+ " ) ";
MapSqlParameterSource param = new MapSqlParameterSource();
param.addValue("id", details.getId());
param.addValue("EMP_NAME", details.getEmpName());
param.addValue("EMP_CODE", details.getEmpCode());
param.addValue("NET_SALARY", details.getNetSalary());
param.addValue("GROSS_EARNING", details.getGrossEarning());
param.addValue("GROSS_DEDUCTION", details.getGrossDeduction());
param.addValue("YYYYMM", details.getYyyymm());
param.addValue("EMP_ID", details.getEmployee() != null ? details.getEmployee().getEmpId() : null);
KeyHolder keyHolder = new GeneratedKeyHolder();
getNamedParameterJdbcTemplate().update(q, param);
// details.setId(((BigDecimal) keyHolder.getKeys().get("ID")).longValue());
}
The main problem is in your query is Not In condition. It will degrade your performance. Try to fetch the "SELECT EMP_ID FROM SALARY_DETAIL_TB" in a separate query and pass in the Not in block in the main query. This will increase the performance of your query. Every time a save is performed this will fire the select query every time.
You have to decide whether you will insert records from SELECT or from the application.
If you don't need to manipulate with data after their select then you can simply call one INSERT INTO SELECT statement without any for cycle. It will be fast because of the only one INSERT statement call.
So you will implement method like copyAllInSalaryDetail(tableSuffix, regionId, circleId) in your SalaryDetailReportDAO and that method will execute INSERT INTO salary_detail_tbl... (...) (SELECT ... WHERE ...) using the same WHERE condition as you have in findAll() method. All inserts will be done only on the Database layer.
If you want to manipulate with data before their insert you can continue with your approach using SalaryDetail bean and for cycle, but you should remove the SELECT part from the INSERT statement and use values from the provided bean. Then the save() method can look like:
#Override
public void save(SalaryDetail details, String tableSuffix) {
// use tableSuffix if it is really needed
String q = "INSERT INTO SALARY_DETAIL_TBL "
+ " (ID "
+ " ,EMP_NAME "
+ " ,EMP_CODE "
+ " ,NET_SALARY "
+ " ,YYYYMM "
+ " ,PAY_CODE "
+ " ,EMP_ID "
+ " ,PAY_CODE_DESC "
+ " ,REMARK "
+ " ,PAY_MODE ) "
+ " VALUES (:id "
+ " ,:emp_name "
+ " ,:emp_code "
+ " ,:net_salary "
+ " ,:yyyymm "
+ " ,:pay_code "
+ " ,:emp_id "
+ " ,:pay_code_desc "
+ " ,:remark "
+ " ,:pay_mode)";
MapSqlParameterSource param = new MapSqlParameterSource();
// KeyHolder keyHolder = new GeneratedKeyHolder();
// details.setId(((BigDecimal) keyHolder.getKeys().get("ID")).longValue());
param.addValue("id", details.getId());
param.addValue("emp_name", details.getEmpName());
param.addValue("emp_code", details.getEmpCode());
param.addValue("net_salary", details.getNetSalary());
param.addValue("pay_code", details.getPayCode());
param.addValue("pay_code_desc", details.getPayCodeDesc());
param.addValue("pay_mode", details.getPayMode());
param.addValue("remark", details.getPayRemark());
param.addValue("yyyymm", details.getYyyymm());
param.addValue("emp_id", details.getEmployee() != null ? details.getEmployee().getEmpId() : null);
getNamedParameterJdbcTemplate().update(q, param);
}

java.lang.IllegalArgumentException: column 'foo' does not exist android

Numerous StackOverflow problems are similar, but it is not an issue of incorrect spacing in the query string. I have two tables, one for peers and one for messages, which has foreign keys associated with ids in the peer table.
Here are my creation strings:
private static final String DATABASE_CREATE = "CREATE TABLE " + PEER_TABLE + " ("
+ PeerContract._ID + " INTEGER PRIMARY KEY, "
+ PeerContract.NAME + " TEXT NOT NULL, "
+ PeerContract.ADDRESS + " TEXT NOT NULL, "
+ PeerContract.PORT + " TEXT NOT NULL);";
private static final String MESSAGE_TABLE_CREATE = "CREATE TABLE " + MESSAGE_TABLE + " ("
+ MessageContract._ID + " INTEGER PRIMARY KEY, "
+ MessageContract.MESSAGE_TEXT + " TEXT NOT NULL, "
+ MessageContract.SENDER + " TEXT NOT NULL, "
+ MessageContract.PEER_FOREIGN_KEY + " INTEGER NOT NULL, "
+ "FOREIGN KEY ("+ MessageContract.PEER_FOREIGN_KEY+") " +
"REFERENCES "+PEER_TABLE+"("+PeerContract._ID+") ON DELETE CASCADE);";
private static final String CREATE_INDEX = "CREATE INDEX " + INDEX + " ON " +
MESSAGE_TABLE + "(" + MessageContract.PEER_FOREIGN_KEY + ");";
I want to query a list of all received messages so I did this:
public Cursor fetchAllMessages(){
String query = "SELECT " + MESSAGE_TABLE + "." + MessageContract._ID + ", "
+ MessageContract.MESSAGE_TEXT + ", "
+ MessageContract.SENDER
+ " FROM " + MESSAGE_TABLE + " JOIN " + PEER_TABLE + " ON "
+ MESSAGE_TABLE + "." + MessageContract.PEER_FOREIGN_KEY
+ "=" + PEER_TABLE + "." + PeerContract._ID;
return db.rawQuery(query, null);
}
Which makes sense to me. And the spacing so far is alright there is no errors.
In my main activity I have a SimpleCursorAdapter:
listView = (ListView) findViewById(R.id.msgList);
dbAdapter = new ServerDbAdapter(this);
dbAdapter.open();
String[] from = new String[] {PeerContract.NAME, MessageContract.MESSAGE_TEXT};
int[] to = new int[] {android.R.id.text1, android.R.id.text2};
cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from, to);
listView.setAdapter(cursorAdapter);
cursor = dbAdapter.fetchAllMessages();
cursorAdapter.swapCursor(cursor);
I get "column 'name' does not exist" and it is driving me crazy!
I properly defined it in DATABASE_CREATE as PeerContract.NAME. I'm guessing its happening because of fetchAllMessages but I am not sure how to fix it.
You are not selecting the PeerContract.NAME, MessageContract.MESSAGE_TEXT in your fetchAllMessages() method. Change it to this:
public Cursor fetchAllMessages(){
String query = "SELECT " + MESSAGE_TABLE + "." + MessageContract._ID + ", "
+ MessageContract.MESSAGE_TEXT + ", "
+ PeerContract.NAME + ", "
+ PeerContract.MESSAGE_TEXT + ", "
+ MessageContract.SENDER
+ " FROM " + MESSAGE_TABLE + " JOIN " + PEER_TABLE + " ON "
+ MESSAGE_TABLE + "." + MessageContract.PEER_FOREIGN_KEY
+ "=" + PEER_TABLE + "." + PeerContract._ID;
return db.rawQuery(query, null);
}

Android: SQLite says a column doesn't exist

I am trying to get all the values in a table that have column _parentbook set to a certain value. When I try to retrieve the entries I get the error shown below.
E/SQLiteLog: (1) table recipes has no column named _parentbook
E/SQLiteDatabase: Error inserting _parentbook=Test _recipemethod=Stir in pot for 20 mins _recipeingredients=No bugs, freedom _recipedescription=Test recipe _recipename=Recipe 1 in Test _recipenotes=Do on Android Studio
The error refers to the method below that I use to add a recipe to the database
public void addRecipe(Recipe recipe) {
ContentValues values = new ContentValues();
values.put(COLUMN_RECIPE_NAME, recipe.getRecipeTitle());
values.put(COLUMN_RECIPE_DESCRIPTION, recipe.getRecipeDescription());
values.put(COLUMN_RECIPE_INGREDIENTS, recipe.getIngredients());
values.put(COLUMN_RECIPE_METHOD, recipe.getMethod());
values.put(COLUMN_RECIPE_NOTES, recipe.getNotes());
//values.put(COLUMN_IMAGE_ID, recipe.getImageId());
values.put(COLUMN_PARENT_BOOK, recipe.getParentBook());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_RECIPES, null, values);
db.close();
}
Code used to initialise TABLE_RECIPES:
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER " +
COLUMN_PARENT_BOOK + " TEXT" +
");";
#Override
public void onCreate(SQLiteDatabase db) {
Log.e(TAG, "OnCreate() called");
db.execSQL(CREATE_TABLE_RECIPES);
}
Method for getting the recipes from the table:
List<Recipe> recipes;
public List<Recipe> getRecipes(String bookName) {
recipes = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
//String query = "SELECT "+ COLUMN_PARENT_BOOK +" FROM " + TABLE_RECIPES + " WHERE " + COLUMN_PARENT_BOOK + "=" + bookName;
String query = "SELECT * FROM " + TABLE_RECIPES;// + " WHERE 1";
// Cursor going to point to a location in the results
Cursor c = db.rawQuery(query, null);
// Move it to the first row of your results
c.moveToFirst();
if (c.moveToFirst()) {
do {
if (c.getString(c.getColumnIndex(COLUMN_RECIPE_NAME)) != null) {
recipes.add(new Recipe(
c.getString(c.getColumnIndex(COLUMN_RECIPE_NAME)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_DESCRIPTION)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_INGREDIENTS)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_METHOD)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_NOTES)),
// Add image here if required
c.getString(c.getColumnIndex(COLUMN_PARENT_BOOK))
));
}
} while (c.moveToNext());
}
db.close();
//c.close();
return recipes;
}
I have tried upgrading the database version and looking at other similar questions on StackOverflow, neither helped.
Thanks.
You forgot to put comma(,) in create table statement.
Instead of
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER " +
COLUMN_PARENT_BOOK + " TEXT" +
");";
It should be
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER, " + // Here you forgot to put comma(,) in this line
COLUMN_PARENT_BOOK + " TEXT" +
");";

onCreate is called as expected. But tables are not created

So I've got this problem which is really annoying me. I override the onCreate method of my class extending SQLiteOpenHelper:
#Override
public void onCreate(SQLiteDatabase db) {
super.onCreate(db);
final String createAccTableCmd = ("CREATE TABLE IF NOT EXISTS " + ACCOUNTS_TABLE_NAME + " ( " +
ACCOUNT_KEY_ID + " INTEGER PRIMARY KEY ASC AUTOINCREMENT, " +
ACCOUNT_KEY_NAME + " TEXT UNIQUE ON CONFLICT IGNORE NOT NULL ON CONFLICT IGNORE, " +
ACCOUNT_KEY_SELECTED + " INTEGER NOT NULL ON CONFLICT IGNORE, " + //THIS IS IN MILLISECONDS
"CHECK (" + ACCOUNT_KEY_SELECTED + " = 0 OR " + ACCOUNT_KEY_SELECTED + " = 1) ON CONFLICT IGNORE" +
" ) ");
final String oneAndOnlyOneSelectedAccInsertTriggerCmd = "CREATE TRIGGER " + ONE_AND_ONLY_ONE_SELECTED_TRIGGER_INSERT_NAME + " " +
"AFTER INSERT ON " + ACCOUNTS_TABLE_NAME + " " +
"FOR EACH ROW " +
"BEGIN " +
"DELETE FROM " + ACCOUNTS_TABLE_NAME + " WHERE " + ACCOUNT_KEY_ID + " = NEW." + ACCOUNT_KEY_ID + "; " +
"END";
final String oneAndOnlyOneSelectedUpdateTriggerCmd = "CREATE TRIGGER " + ONE_AND_ONLY_ONE_SELECTED_TRIGGER_UPDATE_NAME + " " +
"AFTER UPDATE ON " + ACCOUNTS_TABLE_NAME + " " +
"FOR EACH ROW " +
"WHEN (SELECT(SUM(" + ACCOUNT_KEY_ID + ")) <> 1) " +
"BEGIN " +
"UPDATE " + ACCOUNTS_TABLE_NAME + " SET " + ACCOUNT_KEY_SELECTED + " = 0; " +
"UPDATE " + ACCOUNTS_TABLE_NAME + " SET " + ACCOUNT_KEY_SELECTED + " = 1 WHERE " + ACCOUNT_KEY_ID + " = NEW." + ACCOUNT_KEY_ID + "; " +
"END";
synchronized (DB_LOCK) {
db.beginTransaction();
db.execSQL(createAccTableCmd);
db.execSQL(oneAndOnlyOneSelectedAccInsertTriggerCmd);
db.execSQL(oneAndOnlyOneSelectedUpdateTriggerCmd);
addTableName(ACCOUNTS_TABLE_NAME);
ContentValues cv = new ContentValues();
cv.put(ACCOUNT_KEY_ID, 0);
cv.put(ACCOUNT_KEY_NAME, "name");
cv.put(ACCOUNT_KEY_SELECTED, 0);
Log.d("debug", "-1 if error on insert: " + db.insert(ACCOUNTS_TABLE_NAME, "", cv));
Log.d("debug", "Size: " + db.query(ACCOUNTS_TABLE_NAME, null, null, null, null, null, ACCOUNT_KEY_ID + " ASC").getCount());
db.setTransactionSuccessful();
db.endTransaction();
LBackupAgent.requestBackup(mContext);
}
Log.d("debug", "Size after ending the transaction: " + db.query(ACCOUNTS_TABLE_NAME, null, null, null, null, null, ACCOUNT_KEY_ID + " ASC").getCount());
}
One would expect the output of this to be:
-1 if error on insert: 0
Size: 0 /* or 1, if the select takes into account the data not committed of the current transaction, I'm not sure about this */
Size after ending the transaction: 1
When the actual output happens to be:
-1 if error on insert: 0
Size: 0
Size after ending the transaction: 0
How can it be that the insertion is successful but the selection returns 0 rows?
I've checked with a shell that the table does exist, but effectively it is empty, which could be explained by the fact that the tables do not seem to be really existing until onCreate() finishes, justifying as well the 0 returned by the insertion command. Should I guess that this some kind of design constraint to make sure that onCreate does only include CREATE TABLE, CREATE TRIGGER and such type of statements? What if I consider that my schema definition needs an insertion (as is the case)?
Try inserting some dummy values instead of below:
ContentValues defaultAcc = mapAccountToStorable(defaultAccDataModel = new AccountListRecyclerAdapter.AccountDataModel(
LBudgetUtils.getInt(mContext, "default_account_id"),
LBudgetUtils
.getString(mContext, "default_account_name"),
mContext.getResources().getBoolean(
R.bool.default_account_selected)));
Instead of sending nullColumnHack as null send it as "". It will make sure that a row will be created in table even if values are null.
db.insert(ACCOUNTS_TABLE_NAME, "", defaultAcc)
Try below:
db.beginTransaction();
db.execSQL(createAccTableCmd);
db.execSQL(oneAndOnlyOneSelectedAccInsertTriggerCmd);
db.execSQL(oneAndOnlyOneSelectedUpdateTriggerCmd);
db.setTransactionSuccessful();
db.endTransaction();
db.beginTransaction();
addTableName(ACCOUNTS_TABLE_NAME);
AccountListRecyclerAdapter.AccountDataModel defaultAccDataModel;
ContentValues defaultAcc = mapAccountToStorable(defaultAccDataModel = new AccountListRecyclerAdapter.AccountDataModel(LBudgetUtils.getInt(mContext, "default_account_id"), LBudgetUtils.getString(mContext, "default_account_name"), mContext.getResources().getBoolean(R.bool.default_account_selected)));
Log.d("debug", "-1 if error on insert: " + db.insert(ACCOUNTS_TABLE_NAME, null, defaultAcc));
db.setTransactionSuccessful();
db.endTransaction();
Log.d("debug", "Size: " + db.query(ACCOUNTS_TABLE_NAME, null, null, null, null, null, ACCOUNT_KEY_ID + " ASC").getCount());

SQLite java.lang.NullPointerException in only select query

i added sqlite-jdbc-3.7.2.jar to build path. I used insert query. when i opened the wellec.db with notepad, i can see records. But my select is not working.
HERE WellInfo class properties
public Integer wellID;
public Integer measurement;
public String wellname;
public Integer wellstatus;
public String licenseno;
public String gl;
public String kb;
public String spuddate;
public String drillingenddate;
public String totaldepth;
public String notes;
public String easting;
public String northing;
public String coordinatesystem;
public Integer islogadd;
here is my createtable sql
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS WELLINFO " +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ," +
" WELLNAME CHAR(90) NOT NULL, " +
" WELLSTATUS INT NOT NULL," +
" MEASUREMENT INT NOT NULL," +
" ISLOGADD INT NOT NULL," +
" GL CHAR(50) NOT NULL, " +
" KB CHAR(50) NOT NULL, " +
" SPUDDATE CHAR(50) NOT NULL, " +
" TOTALDEPTH CHAR(50) NOT NULL, " +
" LICENSENO CHAR(50) NOT NULL, " +
" DRILLINGENDDATE CHAR(50) NOT NULL, " +
" NOTES CHAR(150) NOT NULL, " +
" EASTING CHAR(50) NOT NULL, " +
" NORTHING CHAR(50) NOT NULL, " +
" COORDINATESYSTEM CHAR(50) NOT NULL)";
stmt.executeUpdate(sql);
...//other tables sql and stmt.executeUpdate(sql)
stmt.close();
c.commit();
here is my insert query which is working. WellInfo wi as parameter
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "INSERT INTO WELLINFO " +
"(ID, WELLNAME, WELLSTATUS , MEASUREMENT, ISLOGADD , GL, KB, SPUDDATE, TOTALDEPTH, " +
"LICENSENO , DRILLINGENDDATE, NOTES, EASTING, NORTHING, COORDINATESYSTEM) " +
"VALUES (NULL,'" + wi.wellname + "'," + wi.wellstatus + "," + wi.measurement + "," +
"" + wi.islogadd +",'" + wi.gl + "','" + wi.kb + "','" + wi.spuddate + "'," +
"'" + wi.totaldepth + "','" + wi.licenseno + "','" + wi.drillingenddate + "', " +
"'" + wi.notes + "','" + wi.easting + "','" + wi.northing + "','" + wi.coordinatesystem + "');";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
return 0;
here is my select
Connection c = null;
Statement stmt = null;
WellInfo[] wi = new WellInfo[60000];
WellInfo[] wi2 = new WellInfo[0];
int i = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
//c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("select * from WELLINFO");
//c.commit();
//if(rs.getRow() > 0)
while ( rs.next() ) { //HERE IS THE PROBLEM
wi[i].wellID = rs.getInt("ID");
i++;
}
wi2 = new WellInfo[i];
for(int j = 0; j < i - 1; j++){
wi2[j] = wi[j];
}
rs.close();
stmt.close();
return wi2;
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
return wi2;
Sorry not specify the problem. Here it is:
SELECT QUERY problem when i call rs.next(), i got the error java.lang.NullPointerException.
wi[i] is null => you can't call wi[i].wellID before you instantiate wi[i], you should do something like
wi[i] = new WellInfo() then call wi[i].wellID

Categories

Resources