SQLite java.lang.NullPointerException in only select query - java

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

Related

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

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 "
+ " )";
}

sql Command has not properly ended

I'm using sql developer and netbeans when ever i try to insert data into the table this error "sql Command has not properly ended".
This is what i tried.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
dbconnection db = new dbconnection();
try {
db.connect();
db.stm = db.con.createStatement();
int result = db.stm.executeUpdate(
"insert into payment values'" + txt_paymentid.getText() + "','" + txt_reservation.getText() +"',
" + "'"+txt_fname.getText()+"',
'"+txt_lname.getText()+"' ,'"+txt_roomid.getText()+"' ,'"+txt_rate.getText()+"' ," + " '"+((JTextField)txt_datein.getDateEditor().getUiComponent()).getText()+"' ,"
+ "'"
((JTextField
)txt_dateout.getDateEditor().getUiComponent()).getText() + "'," + "'" + txt_days.getText() + "','" + txt_payment.getText() + "','" + txt_balance.getText() + "'"
);
if (result > 0) {
JOptionPane.showMessageDialog(this, "Data has been saved succesfully");
} else {
JOptionPane.showMessageDialog(this, "no data has been saved");
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}
For a start
The sql should be in the ()
executeUpdate()("insert...
->
executeUpdate("insert...)
second it looks like the insert command itself it not valid
insert into table values (' ....

How to use question mark PreparedStatement (Java)?

I want to create a java source object in oracle database via JDBC, PreparedStatement. However, in the java source file, there are several question marks. Once I executed it, I faced an error message like below..
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
I changed my code to be more understandable.
private void installOS_COMMAND() {
Connection targetDBconn = null;
PreparedStatement pstmt = null;
Statement stmt = null;
try {
String SQL = "create or replace java source named \"FILE_TYPE_JAVA\" as\n"
+ "public class FileType {\n"
+ " public static String getFileTypeOwner(Connection con) throws Exception {\n"
+ " String sFileTypeOwner = null;\n"
+ " CallableStatement stmt = con.prepareCall(\"begin dbms_utility.name_resolve(?,?,?,?,?,?,?,?); end;\");\n"
+ " stmt.setString(1, \"FILE_TYPE\");\n"
+ " stmt.setInt(2, 7);\n"
+ " stmt.registerOutParameter(3, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(4, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(5, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(6, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(7, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.registerOutParameter(8, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.execute();\n"
+ " sFileTypeOwner = stmt.getString(3);\n"
+ " stmt.close();\n"
+ " return sFileTypeOwner;\n"
+ " }\n"
+ "}";
targetDBconn = globalTargetConn.connect();
pstmt = targetDBconn.prepareStatement(SQL);
pstmt.executeUpdate();
} catch (SQLException ex) { logWriter.writeLogs(logTextArea, LogWriter.ERROR, ex.getMessage());
} finally {
if (pstmt != null ) try {pstmt.close();} catch(SQLException ex) {}
if (targetDBconn != null ) try {targetDBconn.close();} catch(SQLException ex) {}
}
}
Is there someone who can fix this problem?
Don't use prepared statements:
private void installOS_COMMAND() {
Connection targetDBconn = null;
Statement stmt = null;
try {
String SQL = "create or replace java source named \"FILE_TYPE_JAVA\" as\n"
+ "public class FileType {\n"
+ " public static String getFileTypeOwner(Connection con) throws Exception {\n"
+ " String sFileTypeOwner = null;\n"
+ " CallableStatement stmt = con.prepareCall(\"begin dbms_utility.name_resolve(?,?,?,?,?,?,?,?); end;\");\n"
+ " stmt.setString(1, \"FILE_TYPE\");\n"
+ " stmt.setInt(2, 7);\n"
+ " stmt.registerOutParameter(3, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(4, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(5, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(6, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(7, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.registerOutParameter(8, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.execute();\n"
+ " sFileTypeOwner = stmt.getString(3);\n"
+ " stmt.close();\n"
+ " return sFileTypeOwner;\n"
+ " }\n"
+ "}";
targetDBconn = globalTargetConn.connect();
stmt = targetDBconn.createStatement();
stmt.setEscapeProcessing(false);
stmt.executeUpdate(SQL);
} catch (SQLException ex) { logWriter.writeLogs(logTextArea, LogWriter.ERROR, ex.getMessage());
} finally {
if (targetDBconn != null ) try {targetDBconn.close();} catch(SQLException ex) {}
}
}

MySQL deleting code data in Eclipse

I have tables in MySQL and did make connection with this database from Eclipse. I can insert my information into my tables in my MySQL database, but I want the code that can help me for I delete some information from there.
I have this code for inserting but I need the code for deleting:
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection connection = (Connection) DriverManager.
getConnection("jdbc:mysql://localhost/fish", "root", "test");
Statement s = (Statement) connection.createStatement();
s.executeUpdate("insert into fish.store(tr_no,tr_day,tr_month,tr_year,age_type," +
"class,pa_no,first_name,second_name,last_name,age,birth_place," +
" tele_no,address,gender,booking_status) values" +
"('" + fl_no + "','" + day + "','" + month + "','" +
year + "','" + age_type + "','" + fcl + "','" + spa + "'," +
"'" + sfirst + "','" + ssecond + "','" + slast + "','" + sage +
"','" + sP_O_B + "','" + sphone + "'," +
"'" + saddress + "','" + sgender + "','" + status + "')");
Ticket t = new Ticket(sfirst, slast, ssecond, ifl, fcl, day2, month2, year2);
t.setSize(830, 380);
t.setVisible(true);
t.setLocationRelativeTo(null);
t.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
ImagePanel panel = new ImagePanel(new ImageIcon("2.jpg").getImage());
t.getContentPane().add(panel);
} catch(SQLException ex) {
Logger.getLogger(fish.class.getName()).log(Level.SEVERE, null, ex);
}
You can use something like this:
//initialize connection...
String deleteString = "DELETE FROM fish.store WHERE first_name = ? AND last_name = ?";
PreparedStatement deleteStmt = null;
try {
//...
deleteStmt = connection.prepareStatement(deleteString);
deleteStmt.setString(1, "Clint");
deleteStmt.setString(2, "Eastwood");
deleteStmt.executeUpdate();
connection.commit();
} catch...
//close connection
Of course you have to replace the replacement of the statement with your own conditions (deleteStmt.set... (http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html)) and the WHERE clause of the SQL.
Have a look at http://dev.mysql.com/doc/refman/5.1/de/delete.html and http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

MySQLSyntaxErrorException: Unknown column ' ____ ' in 'field list'

I get the following MySQL exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'book.call_Number' in 'field list'.
What does that mean and how can I solve it?
Here is the code responsible for this exception:
public void actionPerformed(ActionEvent e) {
list.clearSelection();
String selectString = " ";
String afName = auth_fName.getText();
String aMI = auth_MI.getText();
String alName = auth_lName.getText();
String tField = titleField.getText();
String sField = subjectField.getText();
try {
Connection conn = Database.getConnection();
Statement s = conn.createStatement();
if (!afName.equals("") && (!aMI.equals("")) && (!alName.equals("")) && (!tField.equals("")) && (!sField.equals(""))) {
selectString = "SELECT a.call_Number as callNbr "
+ "FROM book a "
+ "FULL JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
}
s = conn.createStatement();
System.out.println(selectString);
ResultSet rs = s.executeQuery(selectString);
while (rs.next()) {
String call_Num = rs.getString("call_Number");
String title = rs.getString("title");
String auth_lName = rs.getString("auth_lName");
String auth_MI = rs.getString ("auth_MI");
String auth_fName = rs.getString("auth_fName");
String availability = rs.getString("availability");
view = new View(call_Num, title, auth_lName, auth_MI, auth_fName, availability);
vList.add(view);
System.out.println(view);
}
rs.close();
s.close();
conn.close();
list.setListData(vList.toArray());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Here is the DDL and content:
s.executeUpdate (
"CREATE TABLE book ("
+ "call_Number CHAR(10),"
+ "PRIMARY KEY (call_Number),"
+ "auth_fName CHAR(30)NOT NULL, auth_MI CHAR(2),"
+ "auth_lName CHAR(50)NOT NULL, title CHAR(100) NOT NULL,"
+ "subject CHAR(30) NOT NULL)");
count = s.executeUpdate (
"INSERT INTO book"
+ " VALUES"
+ "('MY.111.000', 'Mark', 'M','Bradshaw','Mystery Under the Sun','mystery'),"
+ "('MY.111.001', 'Mark','','Twain','The Adventures of Huckleberry Finn','mystery'),"
+ "('SF.111.002', 'Kito', 'M','Bradford','Mr. Roboto','science fiction'),"
+ "('SF.111.003', 'Eric','','Laslow','Science Fiction - Can It Happen?','science fiction'),"
+ "('AV.111.004', 'Rashad','','Cheeks','Fire Under the Bridge','adventure'),"
+ "('AV.111.005', 'Samantha','A','Appleby','The Open Sea','adventure'),"
+ "('CO.111.006', 'Lindsey', '','Butterby','What? We cant spend anymore!?','comedy'),"
+ "('CO.111.007', 'Judy', 'S','Yates','So this is life?','comedy'),"
+ "('IN.111.008', 'Elizabeth', 'J','Lee','Mystery Under the Sun','international'),"
+ "('IN.111.009', 'Gabriella', 'M','Rodriguez','Love in Brazil','international')");
*******t_action table***************************
//create transaction table
s.executeUpdate (
"CREATE TABLE t_action ("
+ "patron_ID CHAR(10) NOT NULL,"
+ "call_Number CHAR(10) NOT NULL, check_Out_Date DATE NOT NULL, check_In_Date DATE NOT NULL,"
+ "PRIMARY KEY (patron_ID, call_Number),"
+ "avail CHAR(15), total_Charge FLOAT)");
count3 = s.executeUpdate (
"INSERT INTO t_action"
+ " VALUES"
+ "('P222200000','MY.111.000','2011-03-08','2011-03-15','AVAILABLE',5.00),"
+ "('P222200001','MY.111.001','2011-03-31','2011-04-6','DUE 2011-04-6',5.00),"
+ "('P222200002','SF.111.002','2011-03-30','2011-04-5','DUE 2011-04-5',5.00),"
+ "('P222200003','SF.111.003','2011-03-29','2011-04-4','DUE 2011-04-4',5.00),"
+ "('P222200004','AV.111.004','2011-03-28','2011-04-3','DUE 2011-04-3',5.00),"
+ "('P222200005','AV.111.005','2011-03-27','2011-04-2','DUE 2011-04-2',5.00),"
+ "('P222200006','CO.111.006','2011-03-26','2011-04-1','DUE 2011-04-1',5.00),"
+ "('P222200007','CO.111.007','2011-01-06','2011-01-12','AVAILABLE',5.00),"
+ "('P222200008','IN.111.008','2011-02-06','2011-02-12','AVAILABLE',5.00),"
+ "('P222200009','IN.111.009','2011-03-06','2011-03-12','AVAILABLE',5.00)");
Use a <column> as predicate like below:-
selectString = "SELECT a.call_Number as callNbr, ... "
+ "FROM book a"
+ "FULL JOIN transaction b"
+ "ON a.call_Number=b.call_Number";
And then change the code to look for callNbr :-
String call_Num = rs.getString("callNbr");
HTH.
Change your query to this:
selectString = "SELECT a.call_Number "
+ "FROM book a "
+ "INNER JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
MySQL does not support FULL OUTER JOIN. If you really need the effect of that - you'll need 2 selects with a UNION. Although from looks of it - does not seem like that would be necessary.

Categories

Resources