Issue with prepared statement when using select query with string - java

I have written a simple JDBC program to do a query and trying to create the prepared statement, but the result set is coming as empty. But when the same query executed through general statement creation gives the output and also through SQL plus.
package com.aexp.balu.jdbc;
import java.io.Reader;
import java.sql.*;
public class SimpleConnection {
public static void main(String[] args) {
// TODO Auto-generated method stub
// String url="URL";
// String uname="uname";
// String pass="password";
String url = "URL";
String uname = "uname";
String pass = "password";
String query = "select CARD_NO from MDC.CAS_UNMCH_ROCS where CARD_NO = ?";
String cardNumber = "3222222222222222223";
try {
// step1 load the driver class
System.out.println("registering the driver");
Class.forName("oracle.jdbc.driver.OracleDriver");
// step2 create the connection object . We need to have the type of
// connection
// The DriverManager class has a method get connection which give
// sthe instance of Connection
System.out.println("creating the connection....");
Connection con = DriverManager.getConnection(url, uname, pass);
// step3 create the statement object
System.out.println("creating the statement");
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, cardNumber);
// step4 execute query -- the stmnt object of the method execute
// query results an object
// of result set
System.out.println("Executing the query");
ResultSet rs = stmt.executeQuery();
System.out.println("After Executing the query");
while (rs.next()) {
System.out.println(" in reading result set");
String cardnumber = rs.getString("CARD_NO");
System.out.println(cardNumber);
}
// step5 close the connection object
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The output is like this:
registering the driver
creating the connection....
creating the statement
Executing the query
After Executing the query

Related

Can getString() method of ResultSet can be used for getting the value of a TEXT type column from a MySQL table?

I am trying to retrieve the value of a TEXT field from a table in a MySQL database.
MySQL version is 5.6.21
& I am using mysql-connector-java-5.1.18-bin.jar
My file is given below
import java.sql.*;
public class DatabaseConnection {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/book";
// database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String query;
query = "Select b_name, description columns from brands";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
String first_name = rs.getString("b_name");
String description = rs.getString("description");
System.out.println(first_name);
System.out.println(description);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
} catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
} catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
This says that my column does not exist although I have tried this on another table, it works on VARCHAR columns but not on TEXT columns
This error shows up:
But the table has a column named description:
The problem is NOT about the column type being text.
You can get the value of a TEXT type using getString.
You can verify in the documentation.
The problem is in the query:
query = "Select b_name, description columns from brands";
"columns" there is a mistake.
Written this way, the description column is in fact renamed to columns in your result set.
If you did rs.getString("columns") you would get the value.
But that's not what you want to do. You want to fix the query by dropping that word:
query = "Select b_name, description from brands";

how to insert a variable in SQL which is already defined in the code

public class DB
{
public static void main(.....)
{ String str="hello";
....
st.executeUpdate("insert into r2( col1) values(.....)"); // here r2 is the table in which i want to insert the "str" defined above.
}}
i want to insert this 'str' in the table r2 using the insert command.
WHAT DO I WRITE HERE? TO INSERT VALUE OF "str" PREVIOUSLY DEFINED , how to pass the parameter 'str' from outside such that it gets inserted into the table??
You will write it like this .. assuming column name in table r2 is col1
public class DB
{
public static void main(.....)
{ String str="hello";
.... // Obtain DB Connection here
PreparedStatement ps = connection.prepareStatement("insert into r2( col1) values(?)";
ps.setString(1,str);
ps.execute();
}
}
The safest way is to use a Prepared Statement.
Here is Oracle's very comprehensive tutorial on using Prepared Statements.
In your case (assuming the column you want to insert the value into is named "world") it would be done something like this:
String str="hello";
Connection connection = [...] // Set up connection
String queryString = "insert into r2 ('world') values(?)";
Statement statement = connection.prepareStatement(queryString);
statement.setString(1, str);
statement.executeUpdate();
// Add exception handling, clean-up
Try it and see if it helps.
public class Example {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
PreparedStatement ps = conn.prepareStatement("insert into table_name( col1,col2,col3) values(?,?,?)";
ps.setString(1,str);
ps.setString(2,str);
ps.setString(3,str);
ps.execute();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

JDBC connection is not working with Microsoft Access in corejava

When I execute the program it will execute the catch() part . I have also name the database file as "Database1" also created its source as "Database1", table named "Table1" contain 3 fields of text . Java version and JDBC driver both are 32-bit please help.
import java.sql.*;
class Database
{
// 3 VARIABLES we declare
Connection con; // Get the connection to our database
Statement st; // Access to ur tables inside our database
ResultSet rs; // Access to records in our database
public Database(){
connect();
}
public void connect(){
// To develop Connection
//Every SQL connection throws an exception which we have to handle
try{
// Name for driver
String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; // hold driver for database in this jdbc
//load class
Class.forName(driver);
// Name for Database
String db = "jdbc:odbc:Database1";
// Set Connection
con = DriverManager.getConnection(db);
st = con.createStatement();
String sql = "SELECT * from Table1";
rs = st.executeQuery(sql);
while(rs.next())
{
String fname = rs.getString("FName");
String lname = rs.getString("LName");
String age = rs.getString("Age");
System.out.println(fname+""+lname+""+age+"");
}
}catch(Exception ex){
System.out.println("Exception Catch is running");
}
}
public static void main(String[] args)
{
new Database();
}
}

USER defined java class step in pentaho data integration

Hi,
I am using the below code in USER DEFINED JAVA CLASS:
//STEP 1. Import required packages import java.sql.*;
import org.pentaho.di.core.database.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL ="jdbc:mysql://localhost:1111/mysql";
// Database credentials
static final String USER = "USER";
static final String PASS = "PASS";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null; try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "select id,sorname,src_databasetype,src_databasename from table";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String sorname = rs.getString("sorname");
String src_databasetype = rs.getString("src_databasetype");
String src_databasename = rs.getString("src_databasename");
//Display values
System.out.print("ID: " + id);
System.out.print(", sorname: " + sorname);
System.out.print(", src_databasetype: " + src_databasetype);
System.out.println(", src_databasename: " + src_databasename);
}
rs.close(); }catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace(); }catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace(); }finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample
Running the code through command prompt its working fine
BUT on running the step(In PDI) alone I am getting error:
Non-abstract class "Processor" must implement method "boolean org.pentaho.di.trans.steps.userdefinedjavaclass.TransformClassBase.processRow(org.pentaho.di.trans.step.StepMetaInterface,
org.pentaho.di.trans.step.StepDataInterface) throws
org.pentaho.di.core.exception.KettleException"
For UDJC, I think instead of putting code in the main method, you need to put it in processRow().
Instead of using -
public static void main(String[] args)
use -
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
I am still skeptical if its still going to work as I don't understand what you're trying to do with that code.
Try writing your code in processRow method as follows:
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException{
Object[] r = getRow();
if (r == null) {
setOutputDone();
return false;
}
Object[] outputRow = createOutputRow(r, data.outputRowMeta.size());
//String row = getString(r)+",";
//setValue(outputRow, row)
putRow(data.outputRowMeta, outputRow);
return true;
}

Display rows in database using java

I was trying to display the rows in the database using Java. My idea is to sort the rows in the database and display them in 3 columns and infinite rows. This is what I have. When I run it, I couldn't see any output. Where did I go wrong?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
public class Rows {
public static void main(String[] args) throws SQLException,ClassNotFoundException
{
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
String sql = "select * from site order by fname;";
stmt.execute(sql);
} catch (ClassNotFoundException e) {
System.err.println("Could not load database driver!");
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
if (connection != null)
{
connection.close();
}
}
}
}
The database table I have is
datas(id int, fname varchar(20)
Statement stmt = connection.createStatement();
String sql = "select id, fname from site order by fname;";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
int id=rs.getInt("id");
.............
}
Reference: Retrieving and Modifying Values from Result Sets
The code should obtain a ResultsSet and iterate through it.
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
//You shouldn't need the semi-colon at the end
String sql = "select * from site order by fname;";
//missing piece
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + "\t" + name);
}

Categories