net.ucanaccess.jdbc.UcanaccessSQLException: Column not found: 0 - java

I am new for UCanAccess
package checktpsystemdatabase;
import java.sql.*;
public class CheckTPSystemDatabase {
public static void main(String[] args) throws SQLException {
try {
Connection con = DriverManager.getConnection("jdbc:ucanaccess://D:/Java/TransactionProcessingSystem/src/transactionprocessingsystem/Resources/TPSystem.accdb");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Product");
while (rs.next()) {
System.out.println(rs.getInt(0) + "\t" + rs.getString(1) + "\t" + rs.getString(2));
}
rs.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
When I execute this code, It is showing "net.ucanaccess.jdbc.UcanaccessSQLException: Column not found: 0". Please help me!

You are seeing that error because the numeric index values for a JDBC ResultSet start with 1, not 0. Or, as they say in the "Retrieving Column Values from Rows" section of the Java Tutorial here:
The ResultSet interface declares getter methods (for example, getBoolean and getLong) for retrieving column values from the current row. You can retrieve values using either the index number of the column or the alias or name of the column. The column index is usually more efficient. Columns are numbered from 1
(Emphasis mine.)

simply
the ResultSet rs begins with index 1 not 0 so you should write rs.getInt(1) or rs.getObject(1)

Related

How to call the result of a consult and put it in a Textfield? Mysql + Java

my textfield is called pruebamax
With this function I make the connection with the database
public ResultSet getmax() {
ResultSet r = null;
try {
String sql = "select count(*) as Cantidad from tbl_padre";
System.out.println(sql);
Statement st = cx.createStatement();
r = st.executeQuery(sql);
System.out.println(st.executeQuery(sql));
} catch (SQLException ex) {
Logger.getLogger(Tmrptryone.class.getName()).log(Level.SEVERE, null, ex);
}
return r;
}
his method in the event of a button, with this method I want to print in the textfield the data I receive from the database but I got an error.
public void actualizatext() {
try {
ResultSet r = mrp.getmax();
if (r.next()) {
String ID = r.getString("Cantidad");
pruebamax.setText(ID);
}
} catch (SQLException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
Now, I don't know what pruebamax means but the SQL statement you used:
String sql = "SELECT COUNT(*) AS Cantidad FROM tbl_padre";
is specifically used to count the total number of records currently maintained within the specified database table (tbl_padre). The value from that count will be held in the specified temporary field named: Cantidad. When you Use the SQL COUNT statement you are not going to be returned a String data type value. You will be expected to try and acquire a Integer value.
It will not acquire a value from your table ID field as what it looks like you expect.
To properly retrieve the records count from your applied SQL string then it should be used in this fashion:
int count = 0;
try {
String sql = "SELECT COUNT(*) AS rCount FROM tbl_padre";
Statement st = cx.createStatement();
ResultSet r = st.executeQuery(sql);
while (r.next()) {
count = r.getInt("rCount");
}
r.close();
st.close();
// Close your DB connection as well if desired.
// yourConnection.close();
//To apply this value to your JTextField:
pruebamax.setText(String.valueOf(count));
System.out.println("Total number of records in the tbl_padre " +
" table is: " + count);
}
catch (SQLException ex) {
ex.printStackTrace();
}
Try not to use actual table field names for temporary field names.
If you want to be more specific with your count then your SQL statement must be more specific as well. For example, let's assume that we want to count the number of records maintained in our table where a field named Age contains a value which is greater than 30 years old, our sql statement would look like this:
String sql = "SELECT COUNT(*) AS rCount FROM tbl_padre WHERE Age > 30";
You will of course have noticed the use of the SQL WHERE clause.

Why won't my query run properly? When ever I pass a string variable through the executeQuery method I get an error

There is an error on the line that says ps = stmt.executeQuery();....the error says method executeQuery in interface Statement cannot be applied to given types;
required: String
found: no arguments
reason: actual and formal argument lists differ in length
But whenever I pass a String through that line I get an error saying java.sql.SQLException:Method 'executeQuery(String)' not allowed on prepared statement...
This method is for a button that adds all the Integer values in a column of SQL table.
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {
try{
String SQL = "SELECT SUM(PRICE) FROM MENU";
stmt = con.prepareStatement(SQL);
ps = stmt.executeQuery();
if(ps.next()) {
String total = ps.getString("SUM(PRICE)");
textTotalCost.setText(total);
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(null, err);
}
}
Column name is must while getting a data
Thanks
Updated following the question change
There is no column name explicitly specified for the calculated column SUM(PRICE) in your SQL statement. It would hardly ever actually be "SUM(PRICE)". Try naming your column. Also prepareStatement is useful when passing parameters. Simple Select does not need it:
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {
try{
String SQL = "SELECT SUM(PRICE) As PRICE_TOTAL FROM MENU";
Statement stmt = con.createStatement();
ResultSet ps = stmt.executeQuery(SQL);
if(ps.next()) {
String total = ps.getString("PRICE_TOTAL");
textTotalCost.setText(total);
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(null, err);
}
}
or access the value by column index rather than name:
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {
try{
String SQL = "SELECT SUM(PRICE) FROM MENU";
Statement stmt = con.createStatement();
ResultSet ps = stmt.executeQuery(SQL);
if(ps.next()) {
String total = ps.getString(0);
textTotalCost.setText(total);
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(null, err);
}
}
I don't fully understand your description but I think you are trying to assign the PreparedStatement created in
stmt = con.prepareStatement(SQL)
to a variable of type Statement (stmt) and that's causing the error. The line of code above works because PreparedStatement is an extension (or implementation) of Statement but
ps = stmt.executeQuery();
fails because the class Statement doesn't have an executeQuery method without parameters, PreparedStatement does.
#Y.B.'s solution and the rest of recommendations are good (the alias for sum(price) or getting the value by column index) if it's ok using a regular Statement. The alternative is changing the type of stmt to PreparedStatement in your original code.

java program only gives first column of database table "Users" MSSQL

I am having an issue where i connect to the database,but cannot retrieve more than the first column even though my query statement is "Select * from Users"
below is my code:
import java.sql.*;
public class Connecttodb {
public void dbConnect(String db_connect_string,String db_UserID,String db_UserPass)
{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,db_UserID,db_UserPass);
System.out.println("connected");
Statement statement= conn.createStatement();
String querystring = "SELECT * FROM Users";
ResultSet rs = statement.executeQuery(querystring);
while(rs.next()){
System.out.println(rs.getString(1));
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Connecttodb connServer= new Connecttodb();
connServer.dbConnect("jdbc:sqlserver://TGOURDINE-PC\\SQLEXPRESS;databaseName=picture website", "tgourdine", "thomas");
}
}
the result is only the first column, UserID:
connected
1
2
3
The result i want is as follows:
connected
1 tgourdini thomas NULL NULL
2 Geoff Marley NULL NULL
3 tara Elaine NULL NULL
thank you,
According to the documentation getString(1) will return only the first column.
Because you only retrieve the first column
System.out.println(rs.getString(1));
Change your loop to
while(rs.next())
System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4));
Have a look at the documentation of getString
Retrieves the value of the designated column in the current row of
this ResultSet object as a String in the Java programming language.
Also have a look at the received parameter documentation
columnIndex - the first column is 1, the second is 2, ...

Java invalid cursor type access

public static void insertData() {
String insertFirstName;
String insertLastName;
int id;
Scanner in = new Scanner(System.in);
System.out.println("insert First Name: ");
insertFirstName = in.nextLine();
System.out.println("insert Last Name: ");
insertLastName = in.nextLine();
System.out.println("First name " + insertFirstName + " Last Name "
+ insertLastName);
try {
Statement statement = null;
Class.forName(JDBC_DRIVER);
Connection con = DriverManager.getConnection(DB_URL, "", "");
System.out.println("Connection Successfull");
statement = con.createStatement();
String sql = "Select id, FirstName, LastName FROM PhoneBook";
ResultSet rs = statement.executeQuery(sql);
rs.moveToInsertRow();
rs.next();
while (rs.next()) {
rs.updateString("FirstName", insertFirstName);
rs.updateString("LastName", insertLastName);
rs.insertRow();
}
statement.close();
rs.close();
} catch (Exception e) {
System.out
.println("********************ERROR*********************");
System.out.println(e.getMessage());
}
}
i KEEP getting
******************ERROR*******************
Invalid Cursor Type: 1003
and i dont understand why. i have RS.next() and then i go through the While(rs.next()). What am i doing wrong? Please help thank you
The javadoc of moveToInsertRow() says:
The insert row is a special row associated with an updatable result set
(emphasis mine)
The javadoc of ResultSet says:
A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. The following code fragment, in which con is a valid Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by others, and that is updatable. See ResultSet fields for other options.
You need to open a updateable ResultSet:
statement = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
See the documentation for ResultSet for further information.
Besides that, it looks like you might be moving a bit too far with the rs.next() calls after the rs.moveToInsertRow();. The example in the docs shows how you should do it:
rs.moveToInsertRow(); // moves cursor to the insert row
rs.updateString("FirstName", insertFirstName);
rs.updateString("LastName", insertLastName);
rs.insertRow();

java.sql.SQLException: Fail to convert to internal representation Exception

Please find my below query,
select nvl(max(transaction_id),0) as transaction_id from exception_details;
If I execute the above query through my jdbc code, it is giving me java.sql.SQLException: Fail to convert to internal representation
my JDBC code is as follows:
public int fetchColumnVal(String query) throws SQLException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException, ClassNotFoundException, InstantiationException {
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection(true);
pstmt = con.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
rs.next();
int count=rs.getInt(1);
return count;
} finally {
if (isBatchMode) {
this.cleanResources(null, pstmt);
}
else {
this.cleanResources(con, pstmt);
}
}
}
and the data type for the column transaction_id in the table is NUMBER
if you use #Enumerated without define EnumType.STRING, i.e
#Enumerated(EnumType.STRING)
and your table already contain String data (Varchar), you shall get this error, cos.
default EnumType is ORDINAL, i.e EnumType.ORDINAL.
SQL JDBC/Java setXXX getXXX
NUMERIC java.math.BigDecimal setBigDecimal getBigDecimal
change rs.getInt(1); to rs.getBigDecimal(1);
(or) type cast number to integer in sql like below for oracle:
CAST(id AS integer)
I would like to suggest a more traditional approach for ResultSet count checking.
Initially I tried using:
while (RS.next()) {
RScount = RS.getInt(1);
Set.add(RS.getString(1));
}
But as my SQL result-set was String, Java kept on throwing:
java.sql.SQLException: Fail to convert to internal representation
Then I changed my code to to plain Vanilla:
Declaration, initialized at 0:
Integer RScount = 0; //SQL result set counter
And counter code as:
while (RS.next()) {
RScount++;
Set.add(RS.getString(1));
}
I was getting error like
Exception Foundjava.sql.SQLException: Fail to convert to internal representation.
I have written my code as :
while(res.next())
System.out.println( res.getInt(1) + " "
+ res.getString(2) + " "
+ res.getString(3) + " "
+ res.getString(4));
but my datatype of 1st field in DB was of varchar type.
Then I changed my code to:
while(res.next())
System.out.println( res.getString(1) + " "
+ res.getString(2) + " "
+ res.getString(3) + " "
+ res.getString(4));
then I got all my data.

Categories

Resources