Exception handling in JDBC batch prepared statement - java

I am working with batch prepared statement.
import java.sql.*;
import java.util.Arrays;
public class QryBtch {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test";
static final String USER = "root";
static final String PASS = "roottoor";
public static void main(String[] args) {
Connection conn = null;
int[] results = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
PreparedStatement ps = null;
String query = "insert into mytable (Emp_ID, Emp_Name) values (?,?)";
ps = conn.prepareStatement(query);
String name1 = "Name1";
String name2="Big Big Name Name 1"; //longer than column length
String name3="Name2";
ps.setInt(1, 1);
ps.setString(2, name1);
ps.addBatch();
ps.setInt(1, 2);
ps.setString(2, name2);
ps.addBatch();
ps.setInt(1, 3);
ps.setString(2, name3);
ps.addBatch();
results = ps.executeBatch();
System.out.println(Arrays.toString(results));
conn.close();
}catch(SQLException se){
System.out.println(Arrays.toString(results));
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
I am trying to insert into a table having name defined as 8 character. So as expected my second statement got failed. Is it possible to track the statement that has been failed or the bind values for error handling.

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";

JDBC:MySql connection is not working in Ajax request -Java

I have exactly same function in both Main method and other method JDBC connection is working fine. If I call the other function it throws error java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/wine:
I have included MySql Driver in library [Netbeans];
processRequest method:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String process = (String) request.getParameter("process");
String name = (String) request.getParameter("process");
String phone=(String) request.getParameter("phone");
String email = (String) request.getParameter("email");
String pwd = (String) request.getParameter("pwd");
PrintWriter out = response.getWriter();
out.println("Hello");
signup(out,process,name,email,phone,pwd);
}
signup method:
private static int signup(PrintWriter out,String process,String name,String email,String phone,String pwd){
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wine", "root", "");
out.println("Process Not Found");
if (process == "signup") {
String query = "INSERT INTO user(name,phone,email,password,role) VALUES(?,?,?,?,1)";
stmt = con.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setString(3, email);
stmt.setString(4, pwd);
stmt.execute();
} else {
out.println("Process Not Found");
}
} catch (SQLException e) {
// do something appropriate with the exception, *at least*:
out.println(e);
e.printStackTrace();
return 0;
}
return 1;
}
Main Method :
public static void main(String[] args) {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String process = "signup";
String name = "Test";
String phone="45885";
String email = "Test#gmail.com";
String pwd = "dkjsdh";
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wine", "root", "");
if (process == "signup") {
String query = "INSERT INTO user(name,phone,email,password,role,status) VALUES(?,?,?,?,1,1)";
stmt = con.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setString(3, email);
stmt.setString(4, pwd);
stmt.execute();
} else {
System.out.println("Process Not Found");
}
} catch (SQLException e) {
// do something appropriate with the exception, *at least*:
System.out.println(e);
e.printStackTrace();
}
}
There are two options that can be tried:
Class.forName("com.mysql.jdbc.Driver").newInstance() //older bug
and
Class.forName("com.mysql.jdbc.Driver");
In the comment I pasted the older bug solution when I meant to paste the second one.
Either way I am glad that it worked out for you

JDBC mysql does not support placeholder of LIMIT in PreparedStatement?

I used mysql-connector-java-5.1.38 to operate mysql-community-5.7.10.0 on Windows 10 64-bit.
I try to bind value in limit for pagination
"SELECT * FROM employee LIMIT ?, ?"
However the result shows:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2505)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1370)
at SqlTest.main(SqlTest.java:65)
However, I tried sql in navicat directly but could get the correct answer:
INSERT INTO employee VALUES (1, 'Zara');
INSERT INTO employee VALUES (2, 'Zara');
INSERT INTO employee VALUES (3, 'Zara');
INSERT INTO employee VALUES (4, 'Zara');
SET #skip=1; SET #numrows=5;
PREPARE STMT FROM 'SELECT * FROM employee LIMIT ?, ?';
EXECUTE STMT USING #skip, #numrows;
Here is my entire code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlTest {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/employee?useServerPrepStmts=false";
// Database credentials
static final String USER = "root";
static final String PASS = "whaty123";
static final int PAGESIZE = 10;
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pStmt = null;
// STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// STEP 3: Open a connection
System.out.println("Connecting to database...");
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (SQLException e) {
e.printStackTrace();
}
String insertPreparedSql = "INSERT INTO employee " + "VALUES (?, 'Zara')";
try {
pStmt = conn.prepareStatement(insertPreparedSql);
} catch (SQLException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
try {
pStmt.setInt(1, i);
pStmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
String selectLimitSql = "SELECT * FROM employee LIMIT ?, ?";
// select with limit
try {
pStmt = conn.prepareStatement(selectLimitSql);
pStmt.setFetchSize(PAGESIZE);
pStmt.setMaxRows(PAGESIZE);
pStmt.setFetchDirection(ResultSet.FETCH_FORWARD);
int pageNo = 0;
pStmt.setInt(1, pageNo * PAGESIZE);
pStmt.setInt(2, PAGESIZE);
ResultSet rs = pStmt.executeQuery(selectLimitSql);
while (!rs.wasNull()) {
while(rs.next()) {
System.out.println("id: " + String.valueOf(rs.getInt(1)) + " name: " + rs.getString(2));
}
pageNo = pageNo + 1;
pStmt.setInt(1, pageNo * PAGESIZE);
pStmt.setInt(2, PAGESIZE);
pStmt.executeQuery(selectLimitSql);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Your problem is not about the syntax or MySQL support for LIMIT since it's supported. The problem is about the way you are executing the PreparedStatement.
When using PreparedStatement you may not use the executeQuery(String sql), because you've prepared the SQL string formerly for the execution, and no need to pass it again in the executeQuery() method. So do this
ResultSet rs = pStmt.executeQuery();
instead of
ResultSet rs = pStmt.executeQuery(selectLimitSql);
With passing again the selectLimitSql (like above line), you are ignoring the following lines:
pStmt.setInt(1, pageNo * PAGESIZE);
pStmt.setInt(2, PAGESIZE);
and it is like executing your primitive pure sql which contains '?, ?' place holders and you get that exception.
You do not need to pass the query string. Do this
ResultSet rs = pStmt.executeQuery();
instead of
ResultSet rs = pStmt.executeQuery(selectLimitSql);
Also, remove the following lines as pagination is taken care of limit in query itself.
pStmt.setFetchSize(PAGESIZE);
pStmt.setMaxRows(PAGESIZE);
pStmt.setFetchDirection(ResultSet.FETCH_FORWARD);
Following code works:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlTest {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/company?useServerPrepStmts=false";
// Database credentials
static final String USER = "root";
static final String PASS = "rohan";
static final int PAGESIZE = 10;
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pStmt = null;
// STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// STEP 3: Open a connection
System.out.println("Connecting to database...");
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (SQLException e) {
e.printStackTrace();
}
String insertPreparedSql = "INSERT INTO employee " + "VALUES (?, 'Zara', 'Zara','Zara')";
try {
pStmt = conn.prepareStatement(insertPreparedSql);
} catch (SQLException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
try {
pStmt.setInt(1, i*10);
pStmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
String selectLimitSql = "SELECT * FROM employee limit ?, ?";
// select with limit
try {
pStmt = conn.prepareStatement(selectLimitSql);
int pageNo = 0;
pStmt.setInt(1, pageNo * PAGESIZE);
pStmt.setInt(2, PAGESIZE);
ResultSet rs = pStmt.executeQuery();
while (!rs.wasNull()) {
while(rs.next()) {
System.out.println("id: " + String.valueOf(rs.getInt(1)) + " name: " + rs.getString(2));
}
pageNo = pageNo + 1;
pStmt.setInt(1, pageNo * PAGESIZE);
pStmt.setInt(2, PAGESIZE);
rs = pStmt.executeQuery();
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

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