Unexpected Token: AS (Using UCanAcces.jar) - java

I can't find the mistake, I get this error:
Error: net.ucanaccess.jdbc.UcanaccessSQLException: unexpected token: = required: AS
This is my code. Can you help me find it? Thanks in advance.
package database;
// Imports
import java.sql.*;
public class DBConnect {
// Path to Database
final static String DB = "jdbc:ucanaccess://src/database/DB.accdb";
// Declareren
public static String strAntwoord1;
public void Connect(){
// Initialiseren
Connection con;
Statement s;
ResultSet rs = null;
// Try Database Path/Connection to get Variables
try {
con = DriverManager.getConnection(DB);
s = con.createStatement();
rs = s.executeQuery("SELECT * FROM tblAntwoorden WITH ID=1");
if (rs != null) while ( rs.next() ) {
strAntwoord1 = rs.getString("Antwoord");
if (strAntwoord1 == "Indonesië"){
System.out.println("Antwoord found.");
}
}
s.close();
con.close();
} catch (SQLException e) {
System.out.println("Error: " + e);
}
}
}
It's a task for school and I've got to solve this before midnight. So I've got 1 hour left. Thanks in advance for the people who are willing to help me.

Benji, your SQL has to be perfectioned. Not WITH but WHERE:
SELECT * FROM tblAntwoorden WHERE ID=1
The message says "an alias declaration is expected", e.g.,
SELECT * FROM tblAntwoorden AS a WHERE a.ID=1
yet I hope this suggestion from a different timezone helps you to do the next homework.

Related

ResultSet search Error in JDBC

so I am a beginer in JDBC - SQL Programming. I need a little advice which is most probably about SYNTAX.
So, Problem = I'm trying to search a record which has name(string provided in function argument) in the record. Following is my code. Now I've designed this code in such a way that there can be more than 1 records with the same name, so all of that records' data will be printed (by ShowData() Function).
protected static void SearchbyName (String toCompareName)
{
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
boolean flag = false; //to confirm if record has found atleast once
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT idEmployee FROM employee WHERE name = ' "+toCompareName+" ' ");
if( !(rs.next()) ) //if ResultSet is not empty
{
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
}
if(flag==false) //if no record found
{
JOptionPane.showMessageDialog(null, "ERROR:: No Records Found..", "Not Found", JOptionPane.ERROR_MESSAGE);
}
//close connection
if(rs!=null)
{ rs.close(); }
if(stmt!=null)
{ stmt.close(); }
if(conn!=null)
{ conn.close(); }
}
catch(SQLException e)
{ System.err.println(e); }
catch(Exception e)
{ System.err.println(e); }
}
So here it is. As far as my understanding goes, there is some problem with either RESULTSET rs or the Query I'm executing.
Kindly help. & if you can suggest a better approach for search, sure do please. I'm going to write 4 more functions SearchbyAge, SearchbyQualification, SearchbySpecialization on the same pattern.
Just this is enough
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
You don't have to check the data in resultset this way with a if case
if( !(rs.next()) )
This will move to the next record in the resultset
SOVLED
My error was in query. I was putting spaces in string's syntax which I was comparing.
WRONG = `"(.. WHERE name = " ' +toCompareName+ '" ");
RIGHT = `"(.. WHERE name = "'+toCompareName+'" ");
So thats it. Hope it helps to anyone else. :)

Why I didn't get results when adding Where clause to my query?

I'm using Mysql JDBC driver.. but I have some problem..
the problem is when I use SELECT Query in java source code.
When I use this query:
select * from [name of table]
I've gotten result of query from DB successfully.
but when I use this query:
select * from student where (substring(stu_name,0,1)>= '가' and substring(stu_name,0,1) < '나') ;
I've not gotten result of query from DB..
The difference thing is just that using where or not.
What's the problem?
How can I solve this problem?
this is my code below
this query isn't working
select * from student where (substring(stu_name,0,1)>= '가' and substring(stu_name,0,1) < '나') ;
this query is working very well
select * from student;
The difference thing is just only query information .. rest of the source code is the same absolutely
I added my java source code
public class Center {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String sql = "select * from student where (substring(stu_name,0,1)>= '가' and substring(stu_name,0,1) < '나') ";
String url = "jdbc:mysql://localhost:3306/test";
String driverName = "com.mysql.jdbc.Driver";
String id = "root";
String password = "jsyun0415";
Connection con = null;
PreparedStatement prepareState = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list_second = new ArrayList<String>();
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
System.out.println("Failed to load JDBC driver..");
e.printStackTrace();
return;
}
try {
con = DriverManager.getConnection(url, id, password);
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
list.add(rs.getNString("stu_no"));
list_second.add(rs.getNString("stu_ename"));
}
//test = list.get(2);
} catch (SQLException sqex) {
System.out.println("SQLException: " + sqex.getMessage());
System.out.println("SQLState: " + sqex.getSQLState());
} finally {
try {
if (stmt != null)
stmt.close();
if (con != null)
con.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
You will need to set the the character encoding in the JDBC connection URL:
String url = "jdbc:mysql://localhost:3306/test?useUnicode=yes&characterEncoding=UTF-8";
Otherwise the character encoding between client and server is automatically detected upon connection, this means that the Korean text in your query will be wrongly encoded and will probably cause the query to return zero results.
You can read more about this in the MySQL JDBC driver documentation - Using Character Sets and Unicode
This answer suggests that there's no problem with the Java code; it's your data.
Can you run the query in the MySQL admin tool and get back a result set that's not empty? If yes, there's a problem with your Java code. There must be an error that you either aren't supplying or you swallow with an empty catch block.
Do you get an error message or stack trace, or is the result set empty? If it's the latter, perhaps there is no student row with number 20001001.
MySQL function "substring" parameter 0 is wrong, only more then zero allowed.

Result Set return null value

I'm having a trouble when retrieving in a very simple SELECT query.
I'm trying to retrieve all information from table 'db_con_type' and put them in array String of dbChoices.
Database:
The Select query works fine in report designer. Sorry i can't upload the images since i'm new here.
Code:
public void setDbTypeChoices()
{
try
{
con2db connect2db = new con2db();
con = connect2db.aksesDatabase();
stmt = con.createStatement();
String sql = "SELECT * FROM db_con_type";
rs = stmt.executeQuery(sql);
int i = 0;
while(rs.next())
{
this.dbChoices[i] = rs.getString("DB_Type");
i++;
}
rs.close();
stmt.close();
ps.close();
con.close();
//Close Connection
connect2db.tutupKoneksi();
}
catch(Exception e)
{
System.out.println("SQL ERROR 1 = " + e.getMessage());
System.out.println("SQL ERROR 2 = " + e.toString());
}
}
Error:
SQL ERROR 1 = null
SQL ERROR 2 = java.lang.NullPointerException
Question:
Any idea what is happening? Any Solution?
Thanks
By the way, it is a good practice that if you are handing ResultSet that you first check if the result set returned is not null before operating on it e.g. rs.next() which will give you a NPE if rs is null.
if(rs != null) {
while(rs.next()) {
this.dbChoices[i] = rs.getString("DB_Type");
i++;
}
}
Found the problem. it's because of the ps.close() code..
since i don't use it here but i close it and it rises a problem..
thanks to the printStackTrace idea by Luiggi.
thanks for all answers. i really appreciate it.. :D

Java - Getting Data from MySQL database

I've connected to a MySQL database, which contains four fields (the first of which being an ID, the latter ones each containing varchar strings).
I am trying to get the last row of the database and retrieve the contents of the fields so that I can set them to variables (an int and three strings) and use them later.
So far, I have the bare minimum to make the connection, where do I go from here? As you can see I have tried to write a SQL statement to get the last row but it's all gone wrong from there and I don't know how to split it into the separate fields.
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
st.getResultSet().getRow();
con.close();
Here you go :
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("first_column_name");
String str1 = rs.getString("second_column_name");
}
con.close();
In rs.getInt or rs.getString you can pass column_id starting from 1, but i prefer to pass column_name as its more informative as you don't have to look at database table for which index is what column.
UPDATE : rs.next
boolean next()
throws SQLException
Moves the cursor froward 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.
When a call to the next method returns false, the cursor is positioned
after the last row. Any invocation of a ResultSet method which
requires a current row will result in a SQLException being thrown. If
the result set type is TYPE_FORWARD_ONLY, it is vendor specified
whether their JDBC driver implementation will return false or throw an
SQLException on a subsequent call to next.
If an input stream is open for the current row, a call to the method
next will implicitly close it. A ResultSet object's warning chain is
cleared when a new row is read.
Returns:
true if the new current row is valid; false if there are no more rows Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
reference
Something like this would do:
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/t";
String user = "";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
if (rs.next()) {//get first result
System.out.println(rs.getString(1));//coloumn 1
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
you can iterate over the results with a while like this:
while(rs.next())
{
System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
}
There are many other great tutorial out there like these to list a few:
http://www.vogella.com/articles/MySQLJava/article.html
http://www.java-samples.com/showtutorial.php?tutorialid=9
As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance(); see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver") as its not necessary to initiate it yourself
References:
http://zetcode.com/databases/mysqljavatutorial/
This should work, I think...
ResultSet results = st.executeQuery(sql);
if(results.next()) { //there is a row
int id = results.getInt(1); //ID if its 1st column
String str1 = results.getString(2);
...
}
Easy Java method to get data from MySQL table:
/*
* CREDIT : WWW.CODENIRVANA.IN
*/
String Data(String query){
String get=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306/mysql","root","password");
Statement stmt = (Statement) con.createStatement();
ResultSet rs=stmt.executeQuery(query);
if (rs.next())
{
get = rs.getString("");
}
}
catch(Exception e){
JOptionPane.showMessageDialog (this, e.getMessage());
}
return get;
}
Here is what I just did right now:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.javafx.runtime.VersionInfo;
public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();
public static void main(String args[]) {
getData();
}
public static void getData () {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage",
"root", "root");
// here mynewpage is database name, root is username and password
Statement stmt = con.createStatement();
System.out.println("stmt " + stmt);
ResultSet rs = stmt.executeQuery("select * from carsData");
System.out.println("rs " + rs);
int count = 1;
while (rs.next()) {
String vehicleType = rs.getString("VHCL_TYPE");
System.out.println(count +": " + vehicleType);
count++;
}
con.close();
} catch (Exception e) {
Logger lgr = Logger.getLogger(VersionInfo.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
System.out.println(e.getMessage());
}
}
}
The Above code will get you the first column of the table you have.
This is the table which you might need to create in your MySQL database
CREATE TABLE
carsData
(
VHCL_TYPE CHARACTER(10) NOT NULL,
);
First, Download MySQL connector jar file, This is the latest jar file as of today [mysql-connector-java-8.0.21].
Add the Jar file to your workspace [build path].
Then Create a new Connection object from the DriverManager class, so you could use this Connection object to execute queries.
Define the database name, userName, and Password for your connection.
Use the resultSet to get the data based one the column name from your database table.
Sample code is here:
public class JdbcMySQLExample{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/YOUR_DB_NAME?useSSL=false";
String user = "root";
String password = "root";
String query = "SELECT * from YOUR_TABLE_NAME";
try (Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
System.out.println(ex);
}
}

Understanding mysterious Oracle JDBC errors - ORA-00911: invalid character

I am making Java 1.6-JDBC-Oracle 11 code. I created a table called employee with id,name and age. I am getting the error - ORA-00911: invalid character. How can I fix this ?
Here is my code-
import java.sql.*;
import java.util.Properties;
import java.io.IOException;
import java.io.FileInputStream;
public class HelloOracle {
static String query =
"SELECT emp_id, emp_name, emp_age " +
"FROM employee;";
public static void main(String[] args) {
String username = "";
String password = "";
Properties prop = new Properties();
try {
FileInputStream fis = new FileInputStream("Login.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
username = prop.getProperty("username").trim();
password = prop.getProperty("password").trim();
try {
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#//localhost:1521/xe", username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.print(rs.getString("emp_id"));
System.out.print(" , ");
System.out.print(rs.getString("emp_name"));
System.out.print(" , ");
System.out.print(rs.getString("emp_age"));
System.out.println();
}
} catch (SQLException e) {
System.out.println("Exception: " + e);
}
}
}
Unfortunately, oracle error messages are not as informative as mysql or mssql and I am not able to trouble shoot them easily. I am also not able to see which line of code caused the exception.
Try removing the semi colon from the end of your SQL statement.
ie
static String query = "SELECT emp_id, emp_name, emp_age " +
"FROM employee"; // no trailing ";" in the SQL
Bohemian is exactly right. I don't see why this was so hard. If you pop the message into Google, you'll get this:
http://www.dba-oracle.com/sf_ora_00911_invalid_character.htm
The semi-colon is the first problem noted.
Another recommendation: Don't do this.
catch(SQLException e){System.out.println("Exception: " + e);}
Do this instead:
catch(SQLException e){
e.printStackTrace(); // better yet, log it.
}
It'll give you lots more information.
remove the ; from inside the query

Categories

Resources