jdbc oracle 11g PreparedStatement not producing results - java

I am trying fetch data based on a condition on committee column using jdbc.Using Statement it produces the desired result but using PreparedStatement it does not.I cannot figure out what has gone wrong.Kindly help.Here is both the programs one using Statement and the other one using PreparedStatement and my table structure as well
import java.sql.*;
class SelectPrepared {
public static void main(String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "abcd","abcd");
String sql = "select * from tatuserinfo where committee = 'GENERAL'";
Statement stmt = con.createStatement();
// stmt.setString(1,"GENERAL");//1 specifies the first parameter in the query
ResultSet myRs = stmt.executeQuery(sql);
while (myRs.next()) {
System.out.println(myRs.getString(1) + myRs.getString(2) + myRs.getString(3) + myRs.getString(4)
+ myRs.getString(5) + myRs.getString(6) + myRs.getString(7) + myRs.getString(8));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
import java.sql.*;
class SelectPreparedOne {
public static void main(String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String s = "GENERAL";
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "abcd","abcd");
String sql = "select * from tatuserinfo where committee = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, s);// 1 specifies the first parameter in the query
ResultSet myRs = stmt.executeQuery();
while (myRs.next()) {
System.out.println(myRs.getString(1) + myRs.getString(2) + myRs.getString(3) + myRs.getString(4)
+ myRs.getString(5) + myRs.getString(6) + myRs.getString(7) + myRs.getString(8));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Table structure
USERNAME VARCHAR2(40)
PASSWORD VARCHAR2(40)
ROLE VARCHAR2(40)
NAME VARCHAR2(40)
DESIGNATION VARCHAR2(40)
DEPARTMENT VARCHAR2(40)
EMAILID VARCHAR2(40)
COMMITTEE CHAR(15)

TL/DR: don't use char use varchar2
CHAR(15) gets blank padded to 15 characters, so the column contains the value 'GENERAL ' and that's not equal to the supplied value of 'GENERAL'
The correct fix is to change the column to VARCHAR2(15)
An intermediate ugly workaround (until you fix the column definition) is to use trim:
where trim(committee) = ?;

Related

JDBC connection to MySQL and Sybase database at same time

I am trying to retrieve data from SYBASE database and copy retrieved data in a table in MySQL. I am able to connect both databases separately (i.e) using jTDS driver for SYBASE and Jdbc_driver for MySQL.
Now I want to connect both databases simultaneously in a single program. But I confused what should be written in Class.forName().
I have used Class.forName(JDBC_DRIVER); for MySQL and Class.forName("net.sourceforge.jtds.jdbc.Driver"); for SYBASE.
Sybase:
public static void main(String[] args) {
String a;
String b;
String c;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:jtds:sybase://10.159.252.29:4100/fmdb","sa","Changeme_123");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("selecttbl_alm_log_2000000000.Csn,"
+ "tbl_alm_log_2000000000.IsCleared,"
+ "tbl_alm_log_2000000000.Id"
+ "From fmdb.dbo.tbl_alm_log_2000000000"
+ "Where IsCleared = 0");
while(rs.next()) {
a = rs.getString(1);
b = rs.getString(2);
c = rs.getString(3);
System.out.println(a+" "+b+" "+c);
}
con.close();
} catch(Exception e) {
System.out.println(e);
}
}
MySQL:
try {
Class.forName(JDBC_DRIVER);
System.out.println("connecting to database");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("connected to database successfully");
System.out.println("creating table in given database");
// stmt = conn.createStatement();
String sql = "CREATE TABLE newtable "
+ "(id INTEGER not NULL, "
+ "first VARCHAR(255), "
+ "PRIMARY KEY ( id ))";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
System.out.println("created table in database");
}
These are just snippets. I am just trying to merge above code.
Help me by telling if this is possible or not and sharing some insights into this.
Multiple connections in a single program, can be created like this
public static void main(String[] args) {
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection con1 = DriverManager.getConnection("jdbc:jtds:sybase://10.159.252.29:4100/fmdb","sa","Changeme_123");
Class.forName(JDBC_DRIVER);
Connection con2 = DriverManager.getConnection(DB_URL, USER, PASS);
///After getting both connections, write your code
String a;
String b;
String c;
Statement stmt= con1.createStatement();
ResultSet rs=stmt.executeQuery("select tbl_alm_log_2000000000.Csn, tbl_alm_log_2000000000.IsCleared, tbl_alm_log_2000000000.Id From fmdb.dbo.tbl_alm_log_2000000000 Where IsCleared = 0");
while(rs.next()) ///If your query result is single row, use if instead of while
{
a = rs.getString(1);
b = rs.getString(2);
c = rs.getString(3);
System.out.println(a+" "+b+" "+c);
}
String sql = "CREATE TABLE newtable " + "(id INTEGER not NULL, " + "first VARCHAR(255), " + "PRIMARY KEY ( id ))";
stmt = con2.prepareStatement(sql);
stmt.executeUpdate(sql);
con1.close();
con2.close();
}catch(Exception e){ System.out.println(e);}
}
}
the suggestion is to divide a complex task into smaller and more simple tasks:
1)create a method readDB(int startReading, int endReading)with return as ResultSet
2)create a method writeDB(ResultSet result)
3)create a method createTableDB()
P.S. readDB is close to your first example and have to return the read of db, writeDB have only to write inside a db some tutorial, and then createTableDB have to make the table on db like you write in your second example.
pseudo final code, in main:
createTableDB();
// it's good to make a loop for next part:
ResultSet read1=readDB(0,200);
writeDB(read1);
ResultSet read2=readDB(200,400);
writeDB(read2);
ResultSet read3=readDB(400,....); //to the end of db
writeDB(read3);
this is a realy simple solution, it is not perfect and can be modified according to your needs.

Java SQLite Select Query

I am trying to complete my Java Code to execute a SELECT Query that will write the Results into Sysout.
Here is my Code:
public void PullFromDB() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
String sql = "SELECT * FROM " + Name + ";";
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
Integer ID = rs.getInt("id");
System.out.println("ID = " + ID.toString());
String entry = rs.getString(Properties.get(j));
System.out.println(Properties.get(j) + "=" + entry);
j++;
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
When I sysout my SQL Query it looks like this:
CREATE TABLE IF NOT EXISTS Cars(ID INTEGER PRIMARY KEY AUTOINCREMENT,AnzSitze TEXT,Marke TEXT,Pferdestärke TEXT);
INSERT INTO Cars(AnzSitze,Marke,Pferdestärke) VALUES('vier','Audi','420');
SELECT * FROM Cars;
Those are just some examples I put in.
maybe create and propabley insert has failed, i see none-ascii characters in filed name Pferdestärke try to use valid names
check this
Permitted characters in unquoted identifiers:
ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar,
underscore)
Extended: U+0080 .. U+FFFF
so replace the filed name Pferdestärke to Pferdestarke in all qrys and try again

class to connect java program to database(which accepts parameters)

I'm trying to write a class that will accept two strings and an int (username and password and score) from a quizgame, which eventually will come from a GUI, at the minute I'm just passing them through from the main, and pass them into a database to be inserted.
I have the JConnector jar file added and am working in Eclipse.
Here is my code
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
//public
class DbConnect {
private java.sql.Connection con;
private java.sql.Statement st;
private ResultSet rs;
public DbConnect() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3307/nostalgic", "root", "usbw");
st = con.createStatement();
} catch (Exception ex) {
System.out.println("Error is " + ex);
}
}
public void setData(String n, String p, int x) {
try {
String query = "select * from nostalgic";
String query1 = "INSERT INTO nostalgic values (n,p,x)";
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.executeUpdate();
rs = st.executeQuery(query);
System.out.println("records from database");
while (rs.next()) {
String name1 = rs.getString("name");
String pw = rs.getString("password");
int score = rs.getInt("score");
System.out.println("Name : " + name1);
System.out.println("Password : " + pw);
System.out.println("Score : " + score);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
The error I get is
Unknown column 'n' in 'field list'
I can directly put a string in like 'john' but that is no use to me in this situation.
Instead of INSERT INTO nostalgic values (n,p,x) you should have
INSERT INTO nostalgic values (?,?,?) and then:
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.setString(1,n);
statement3.setString(2,p);
statement3.setString(3,x);
statement3.executeUpdate();
in
String query1 = "INSERT INTO nostalgic values (n,p,x)";
n,p,x are not being replaced with the values, they are just being considered as some char that's why you get this error
Edit : before statement3.executeUpdate();
String query1 = "INSERT INTO nostalgic values (?,?,?)";
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.setString(1,n);
statement3.setString(2,p);
statement3.setInt(3,x);
Update: you may wonder why Unknown column 'n' in 'field list'?
Because as insert query in sql can have this structure
INSERT INTO table (col1,col2,...) values (`val1`,`val2`,....)
but then values need to be inside `` if hard coded so if there is no `` sign they are considered as column name.
Mick,
the problem is that you don't pass actual parameters to your query when doing statement3.executeUpdate();. Check this link to see how to do it: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html.
You cannot do it like that try this:
Class.forName("com.mysql.jdbc.Driver");
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/nostalgic","root","usbw") {
PreparedStatement pr = null;
String query = "INSERT INTO nostalgic VALUES ((?), (?), (?))";
pr = con.prepareStatement(query);
pr.setString(1, n);
pr.setString(2, p);
pr.setString(3, x);
int status = pr.executeUpdate();
}catch (ClassNotFoundException | SQLException e) {
System.out.println(e.getMessage());
}
There are some mistakes in your code...
Correct imports
Insert statement
Your code will be like that:
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.jdbc.Statement;
// you imported sql innecessary statements...
//public
class DbConnect {
// dont need complete path, you already imported it
private Connection con;
private Statement st;
private ResultSet rs;
public DbConnect() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3307/nostalgic", "root", "usbw");
st = con.createStatement();
} catch (Exception ex) {
System.out.println("Error is " + ex);
}
}
public void setData(String n, String p, int x) {
try {
String query = "select * from nostalgic";
String query1 = "INSERT INTO nostalgic values (?,?,?)";
// no need to define vars here,
// just number of places to be inserted here ----^
PreparedStatement statement = con.prepareStatement(query1);
// prepare statement
statement = con.prepareStatement(query);
// insert the variables in places you prepared before
// and matching the types you need!!!
statement.setString(1,n);
statement.setString(2,p);
statement.setInt(3,x);
rs = st.executeQuery(query);
System.out.println("records from database");
while (rs.next()) {
String name1 = rs.getString("name");
String pw = rs.getString("password");
int score = rs.getInt("score");
System.out.println("Name : " + name1);
System.out.println("Password : " + pw);
System.out.println("Score : " + score);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}

ResultSet.next() Throwing SQLException: Result Set Closed

I've tried to debug the code and read the Oracle doc and I don't see any reason why the result set would be closed.
Statement statement = DatabaseConnector.connect();
String sql = "Select * from Room where Room_Type like '*"+roomType+"*' "+availability;
boolean foundResults = statement.execute(sql);
if(foundResults){
ResultSet rs = statement.getResultSet();
StringBuilder row = new StringBuilder();
if(rs!=null){
while(rs.next()){
RE: SQLException
I'm not quite sure what DatabaseConnector is supposed to do in the question code, but the following test code works for me.
RE: Wildcard character
When using the LIKE operator in a query from within the Access application itself then the asterisk * is the wildcard character to use. When querying an ACE (Access) database from some other application one needs to use the "standard" percent % wildcard character. Note that the following code uses %; using * won't work here.
import java.sql.*;
public class JDBCQuery {
public static void main( String args[] )
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
"Dbq=C:\\Users\\Public\\Database1.accdb;");
String RoomTypeToMatch = "suite";
PreparedStatement s = conn.prepareStatement(
"SELECT Room_No, Room_Type " +
"FROM Room WHERE Room_Type LIKE ?"
);
s.setString(1, "%" + RoomTypeToMatch + "%");
s.execute();
ResultSet rs = s.getResultSet();
if (rs!=null)
{
while (rs.next())
{
System.out.println("[Room_No]: " + rs.getString(1) +
", [Room_Type]: " + rs.getString(2));
}
}
s.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
SQL LIKE wildcard charcaters are represented as % not *
String sql =
"Select * from Room where Room_Type like '%"+roomType+ "%' "+availability;
Aside: Always use a PreparedStatement to project against SQL Injection attacks

ERROR: java.sql.SQLException: [Microsoft][ODBC dBASE Driver] Too few parameters. Expected 1

I am using MS Access 2007 and trying to insert the data and I am getting the exception and I have tried it by using [] braces but it is not working.It create the DBF file successfully but not generating the exact Output.
import java.sql.*;
public class Test
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dataSourceName = "mdbTEST";
String dbURL = "jdbc:odbc:" + dataSourceName;
Connection con = DriverManager.getConnection(dbURL, "","");
// creating a java.sql.Statement so I can run queries
Statement s = con.createStatement();
s.execute("create table TESTME ( olumn_name integer )");
// creating a table
// inserting some data into the table
s.execute("insert into TESTME values(3)");
// selecting the data from the table
s.execute("[select column_name from TESTME]");
//getting any ResultSet that came from our query
ResultSet rs = s.getResultSet();
if (rs != null)
// if rs == null, then there is no ResultSet to view
while ( rs.next() )
{
/* the next line will get the first column in our current row's ResultSet
as a String ( getString( columnNumber) ) and output it to the screen */
System.out.println("[Data from column_name:]" + rs.getString(1) );
}
s.execute("drop table TESTME");
s.close();
con.close();
}
catch (Exception err)
{
System.out.println("ERROR: " + err);
}
}
}
Your statement
s.execute("[select column_name from TESTME]");
won't work because Access SQL uses square brackets to delimit table and column names, so your SQL "query" consists of a single name with no SELECT keyword. I'd suggest...
s.execute("SELECT [column_name] FROM [TESTME]");
...but that probably won't work because of a typo in your CREATE TABLE statement. Try this:
s.execute("SELECT [olumn_name] FROM [TESTME]");
Edit
The following code works for me:
import java.sql.*;
public class JDBCQuery {
public static void main( String args[] )
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\Public\\Database1.accdb;");
Statement s = conn.createStatement();
s.execute("CREATE TABLE [TESTME] ([column_name] integer)");
s.execute("INSERT INTO [TESTME] VALUES (3)");
s.execute("SELECT [column_name] FROM [TESTME]");
ResultSet rs = s.getResultSet();
if (rs!=null)
{
while (rs.next())
{
System.out.println("Data from column_name: " + rs.getString(1));
}
}
s.execute("DROP TABLE [TESTME]");
s.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
(Note that the database file Database1.accdb already existed when I ran this code.)

Categories