I'm using the jtbs.jdbc.Driver to verify that a proxy number is stored in my MySQL database.
The problem is that whenever I try to copy the curtain row from the table and put it in my ResultSet, the error says that
there is no current row in the ResultSet
The error is at line 31 String value = result.getString(i);
i have been looking all over the web for answers but none of them seem to help my specific predicament.
UP DATE
so far i added a while(result.next()) and it basically dose nothing the while(result.next()) dose not execute.
Here's my code!!!
package dataBata;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class apples {
ArrayList<String> myList = new ArrayList<String>();
String proxNumber = "2435847564";
String usersName = "user";
String password = "pass";
public void wrightMatchdb(){
Connection conn = null;
String url = "jdbc:jtds:sqlserver://localhost:1433/model";
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection(url, usersName, password);
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("select replace(PROXID , ' ','') PROXID ,FIRST_NAME from OKWC_IDCARDS where PROXID = '" + proxNumber + "'");
System.out.println("hello");
while(result.next()){
for(int i=1;i<=6;i++){
System.out.println("hello2");
String value = result.getString(i);
if(result.getString(i) != null){
value = value.replace(" ","");
myList.add(value);
}
String userProx=myList.get(i);
String userFName=myList.get(i+1);
JOptionPane.showMessageDialog(null, userProx + " has a match for", "hi " + userFName, JOptionPane.DEFAULT_OPTION);
}
System.out.println("hello3");
};
System.out.println("hello4");
statement.close();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (conn != null) try { conn.close(); } catch(Exception e) {}
}
}
public static void main(String[] args){
apples A = new apples();
A.wrightMatchdb();
}
}
You need to call result.next() before calling result.getString(i)
Moves the cursor forward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
As far as I can see, your query returns only 2 columns so if you call result.getString(i), make sure that i is either 1 or 2 otherwise you will get an exception.
Related
I'm in a Java class and the assignment is to create a table that will show the first ten values of pre-selected columns. However, when I run my code, with the sql running the way it is it says that my table is already created. I was wondering if there was a way for it to stop erroring out when that happens and to still show my code? Also when I set up a new table, the values that I need, (Income, ID, Pep) won't show up, just the headers I established before the syntax will. How would I make these fixes so it stops erroring out and I see my values in the console log?
This is running in eclipse, extended with prior project files from the class i'm taking. I've tried adding prepared statements, attempted to parse for strings to other variables and attempted syntax to achieve the values I need.
LoanProccessing.java file (Main file):
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class LoanProcessing extends BankRecords {
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
BankRecords br = new BankRecords();
br.readData();
Dao dao = new Dao();
dao.createTable();
dao.insertRecords(torbs); // perform inserts
ResultSet rs = dao.retrieveRecords();
System.out.println("ID\t\tINCOME\t\tPEP");
try {
while (rs.next()) {
String ID= rs.getString(2);
double income=rs.getDouble(3);
String pep=rs.getString(4);
System.out.println(ID + "\t" + income + "\t" + pep);
}
}
catch (SQLException e ) {
e.printStackTrace();
}
String s = "";
s=String.format("%10s\t %10s \t%10s \t%10s \t%10s \t%10s ", rs.getString(2), rs.getDouble(3), rs.getString(4));
System.out.println(s);
String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println("Cur dt=" + timeStamp);
Dao.java file:
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Dao {
//Declare DB objects
DBConnect conn = null;
Statement stmt = null;
// constructor
public Dao() { //create db object instance
conn = new DBConnect();
}
public void createTable() {
try {
// Open a connection
System.out.println("Connecting to a selected database to create Table...");
System.out.println("Connected database successfully...");
// Execute create query
System.out.println("Creating table in given database...");
stmt = conn.connect().createStatement();
String sql = "CREATE TABLE A_BILL__tab " + "(pid INTEGER not NULL AUTO_INCREMENT, " + " id VARCHAR(10), " + " income numeric(8,2), " + " pep VARCHAR(4), " + " PRIMARY KEY ( pid ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
conn.connect().close(); //close db connection
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
}
}
public void insertRecords(BankRecords[] torbs) {
try {
// Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.connect().createStatement();
String sql = null;
// Include all object data to the database table
for (int i = 0; i < torbs.length; ++i) {
// finish string assignment to insert all object data
// (id, income, pep) into your database table
String ID = torbs[i].getID();
double income=torbs[i].getIncome();
String pep=torbs[i].getPep();
sql = "INSERT INTO A_BILL__tab(ID,INCOME, PEP) " + "VALUES (' "+ID+" ', ' "+income+" ', ' "+pep+" ' )";
stmt.executeUpdate(sql);
}
conn.connect().close();
} catch (SQLException se) { se.printStackTrace(); }
}
public ResultSet retrieveRecords() {
ResultSet rs = null;
try {
stmt = conn.connect().createStatement();
System.out.println("Retrieving records from table...");
String sql = "SELECT ID,income,pep from A_BILL__tab order by pep desc";
rs = stmt.executeQuery(sql);
conn.connect().close();
} catch (SQLException se) { se.printStackTrace();
}
return rs;
}
}
Expected results would be printlns for the table functions (inserting records and so on), the headings, the data values for the first 10 files, and the date and time of when the program was run. Actual results were some of the table functions, headings and then the time when the program ran not including when it errors me out with table already created. I'm not exactly sure where or how to fix these issues.
you're getting this exception because every time you run your code, your main method calls dao.createTable();, and if the table is already created, it will throw an exception. So for this part, use a verification to check if the table is already created.
I'm not really sure where you created the variable torbs, but also make sure its properties are not null before inserting them to the database.
i want to display messages with the sender name. The outer while loop is working fine but there is some problem in the inner while loop. I have tried a lot to figure out but got no result. Can anyone help me? I'll very thankful.
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class Messages extends Login {
static Scanner in = new Scanner(System.in);
public static void main(String args[]) throws Exception{
boolean isLoggedin = login();
String msg = "";
String senName = "";
if(isLoggedin) {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?verifyServerCertificate=false&useSSL=false", "root", "");
Statement st = con.createStatement();
Statement st1 = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM chat");
ResultSet rs1 = st1.executeQuery("SELECT * FROM data");
while(rs.next()) {
int dbRecID = rs.getInt("reciever_id");
if(dbRecID == user_id) {
msg = rs.getString("message");
int dbSenID = rs.getInt("sender_id");
while(rs1.next()) {
int senID = rs1.getInt("id");
if(senID == dbSenID) {
senName = rs1.getString("name");
}
}
System.out.println(senName+" sent you a message: "+msg);
}
}
}
else {
System.out.print("Login Unsuccessful");
}
}
}
Output
Ali Ahmed sent you a message: How are you?
Ali Ahmed sent you a message: Hi!
Required Output
Ali Ahmed sent you a message: How are you?
Hamza sent you a message: Hi!
The issue comes from the two nested while loops.
The query ResultSet rs1 = st1.executeQuery("SELECT * FROM data"); is executed just once.
The first time you loop on while(rs.next()) you will fetch the whole content of rs1 to check if the sender id is the right one.
Then on the second iteration on while(rs.next()) because rs1 has been already fetched while(rs1.next()) wil return false.
In order to have your code working you should move the execution of the second query to get something like this:
while(rs.next()) {
...
ResultSet rs1 = st1.executeQuery("SELECT * FROM data");
while(rs1.next()) {
...
}
...
}
But I think that it would be a better solution to make just one SQL
request joining the datas of the two tables and including the where
condition.
I keep getting the following error when I try to upload my books table through eclipse:
java.sql.SQLSyntaxErrorException: ORA-01722: invalid number
I have been able to upload other tables in my database using this basic code, just not this one.
I think it might be something to do with how I am uploading my dates, but I am not sure.
package uploadDatabase;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import oracle.jdbc.OracleDriver;
import java.sql.DatabaseMetaData;
import java.sql.Date;
public class StatesTable {
public static void main(String[] args) {
//private static Connection connection;
try{
DriverManager.registerDriver(new OracleDriver());
//make strings for database connections
String url = "jdbc:oracle:thin:#localhost:1521:xe";
String userName = "BOOKSTORE";
String password = "***********";
//make database connection
Connection conn = DriverManager.getConnection(url,userName,password);
DatabaseMetaData meta = conn.getMetaData();
System.out.println(meta.getDatabaseProductVersion());
String isbn[] = {"00000000110","00000000111","00000000112","00000000113","00000000114"};
String title[] = {"THE SHINING", "THE GIRL WITH THE DRAGON TATTO", "PRIDE AND PREJUDICE", "BOSSYPANTS", "THE HUNGER GAMES"};
String author[] = {"STEPHEN KING", "STIEG LARSSON", "JANE AUSTEN", "TINA FEY", "SUZANNE COLLINS"};
String publishDate[] ={"19750115","19990805","18731015","20160105","19821115"};
String edition[] = {"6TH","3RD","26TH","1ST","7TH"};
double cost[] = {15.75,17.95,8.95,9.95,12.95};
String genre[] = {"HORROR", "MYSTERY", "ROMANCE","COMEDY", "ACTION"};
//Database statement for inserting values into BOOKS table
String sqlStatement = "INSERT INTO BOOKS VALUES(?,?,?,?,?,?,?)";
//Prepared statement for database connection
PreparedStatement pstmt = conn.prepareStatement(sqlStatement);
//loop uploads data into database;
for(int i = 0; i < 5; i++){
//insert values into dbms statement
String isb = isbn[i];
String tit = title[i];
String auth = author[i];
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
java.util.Date parsed = df.parse(publishDate[i]);
Date publishDat = new Date(parsed.getTime());
System.out.println(publishDat);
String editio = edition[i];
double cos = cost[i];
String gen = genre[i];
pstmt.setString(1,isb);
pstmt.setString(2,tit);
pstmt.setString(3,auth);
pstmt.setDate(4,publishDat);
pstmt.setString(5,editio);
pstmt.setDouble(6, cos);
pstmt.setString(7, gen);
//Execute update
pstmt.executeUpdate();
}
//close pstmt statement
pstmt.close();
//close database connection
conn.close();
}
catch(SQLException e){
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The reason you are getting this error is because one of the column data types you are passing into the insert command is not the same as what is actually defined. Make sure to check your table and it's column values and data types and make sure those data types align with which you are trying to insert into that database. As what Andreas said in the comment below you should ALWAYS name your columns in INSERT statements, without them you will not know what is going into your database. Hope this helps :)
I have this testing code that im trying to use to print the result set from my database table in MySQL. Right now It is printing the following.
Connecting database...
Database connected!
com.mysql.jdbc.StatementImpl#6f5f1a42
I am not sure why it is not printing the table columns and values in my db.
here is the code.
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
class Test {
public static void main (String [] args) throws SQLException {
// jdbc:mysql://localhost:3306/mysqldb
String url = "jdbc:mysql://localhost:3306/mysqldb?useSSL=false";
String username = "joker";
String password = "joker";
System.out.println("Connecting database...");
Connection connection = null;
try {
connection = (Connection) DriverManager.getConnection(url, username, password);
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
Statement stmt = (Statement) connection.createStatement();
ResultSet rs = stmt.executeQuery("Select * FROM pet");
System.out.println(rs.getStatement().toString());
stmt.close();
close(connection);
}
public static void close(Connection con){
if(con != null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
After your execute query, you should do something like this
while (rs.next()) {
System.out.println(rs.getInt("column name");)}
Change get operation by column data type. exp: rs.getString, rs.getDouble etc.
check this link for further information
From the docs, the ResultSet merely represents the returned data:
A table of data representing a database result set, which is usually
generated by executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of
data. Initially the cursor is positioned before the first row. The
next method moves the cursor to the next row, and because it returns
false when there are no more rows in the ResultSet object, it can be
used in a while loop to iterate through the result set.
As such, you need to iterate through the result set if you are interested in the data returned from your query using the respective getters such as getString or getInt:
while (rs.next()) {
System.out.println(rs.getInt("Id"));
System.out.println(rs.getString("Name"));
}
You have to iterate over ResultSet
while (rs.next()) {
System.out.println(rs.getString("Col1")); // or rs.getString(0);
System.out.println(rs.getString("Col2"));
System.out.println(rs.getString("ColN"));
}
The output com.mysql.jdbc.StatementImpl#6f5f1a42 looks like the output of the default toString method inherited from the Object class. This is what gets invoked if the ResultSet class you're using doesn't implement its own toString method.
To print out rows and columns, you're going to have to iterate over the result set yourself. For example:
while (rs.next()) {
System.out.println(rs.getXXX(...));
...
}
To print the column names please use the below code
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++ ) {
String name = rsmd.getColumnName(i);
}
Similarly you may also fetch the data by either providing column number or name in a loop
ResultSet rs = st.getResultSet();
try {
while (rs.next()) {
int id = rs.getInt(1);
String userName = rs.getString(2);
String firstName = rs.getString(3);
String surname = rs.getString(4);
Timestamp timeReg = rs.getTimestamp(5);
// ... do something with these variables ...
}
} finally {
rs.close();
}
First up all you have to load the JDBC Driver Class using Class.forName().
Class.forName() load a given Java class in JVM and it also exit in your classpath.
the complete synatx is just like:- Class.forName("com.mysql.jdbc.Driver");
I made a class Test which counts the number of entries corresponding to the user id in the database (calling each entry an email). I used 11120059 as id and number of entries corresponding to this in the database is 2. The output of countMail function is working perfectly but because i am returning an array from getMail() function and taking it into new array, it is showing me null pointer exception. Please help I am stuck in middle of this. The code is:
package src.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import model.Email;
import model.User;
public class Test {
public int countMail(User user){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Get a connection to the database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chillmaarodb", "root", "rsystems");
PreparedStatement myStatement = myConn.prepareStatement("select * from complaints where RID=? ORDER BY date desc");
myStatement.setString(1, user.getId());
ResultSet rs = myStatement.executeQuery();
int count=0;
while(rs.next())
{
count++;
}
return count;
}
catch(Exception e){
e.printStackTrace();
}
return 0;
}
public Email[] getMail(User user){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Get a connection to the database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chillmaarodb", "root", "rsystems");
PreparedStatement myStatement = myConn.prepareStatement("select * from complaints where RID=? ORDER BY date desc");
myStatement.setString(1, user.getId());
ResultSet rs = myStatement.executeQuery();
Home home= new Home();
int length = home.countMail(user);
Email[] mail = new Email[length];
int i=0;
while(rs.next())
{
mail[i].setMessage((String) rs.getString(5));
mail[i].setTitle((String) rs.getString(4));
mail[i].setSender((String) rs.getString(2));
mail[i].setReceiver((String) rs.getString(1));
i++;
}
return mail;
}
catch (Exception e){
e.printStackTrace();
}
Email[] dummyMail = new Email[1];
return dummyMail;
}
public static void main(String[] args){
Test test = new Test();
User user = new User();
user.setId("11120059");
System.out.println(test.countMail(user));
Email[] email = test.getMail(user);
for (int i=0 ; i<test.countMail(user) ; i++){
System.out.println(email[i].getSender());
}
}
}
And the output is:
2
java.lang.NullPointerException
at src.service.Test.getMail(Test.java:73)
at src.service.Test.main(Test.java:107)
Exception in thread "main" java.lang.NullPointerException
at src.service.Test.main(Test.java:111)
When you write Email[] mail = new Email[length]; you create an array of given length which contains null references. You cannot automatically create all the objects for that array by this command. Add mail[i] = new Email() statement:
Email[] mail = new Email[length];
int i=0;
while(rs.next())
{
mail[i] = new Email(); // or use appropriate constructor parameters
mail[i].setMessage((String) rs.getString(5));
mail[i].setTitle((String) rs.getString(4));
mail[i].setSender((String) rs.getString(2));
mail[i].setReceiver((String) rs.getString(1));
i++;
}
Also note that when you create a dummyMail array, it's also an array with single null-reference, the Email object is not created there as well. Probably you need:
Email[] dummyMail = new Email[] {new Email()};