Write Time In MySQL - java

I'm using Java code to randomly create pins for 6000 entries. Currently its taking 3 min 27 sec to write to the database. I would like to know if you can decrease the write time to the database
Database has an auto_increment field as well as a pin field which is a string.
public class DonkeyInsert {
/**
* #param args the command line arguments
* #throws java.sql.SQLException
*/
public static void main(String[] args) throws SQLException {
// TODO code application logic here
Connection conn = new DBConnection().connect();
for (int i = 1; i <= 6000; i++) {
Random rand = new Random();
// create a Statement from the connection
Statement statement = conn.createStatement();
// insert the data
int k = rand.nextInt(Integer.SIZE - 1);
k = (k + 1) * 9999;
String pin = Integer.toString(k);
try {
String sql = "INSERT INTO login (login_id,pin) VALUES (" + i + "," + pin + ");";
statement.executeUpdate(sql);
} catch (SQLException se) {
System.out.println(se);
}
}
}
}

Try this and see if it's faster. The changes I've made should help:
package persistence;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;
/**
* DonkeyInsert changes
* #author Michael
* #link https://stackoverflow.com/questions/32551895/write-time-in-mysql?noredirect=1#comment52959887_32551895
* #since 9/13/2015 12:49 PM
*/
public class DonkeyInsert {
public static final int DEFAULT__RECORD_COUNT = 6000;
private Random random;
public DonkeyInsert() {
this.random = new Random();
}
public DonkeyInsert(long seed) {
this.random = new Random(seed);
}
public static void main(String[] args) {
// I'd externalize these so I could change the database without recompiling.
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://hostname:3306/dbname";
String username = "username";
String password = "password";
Connection connection = null;
try {
DonkeyInsert donkeyInsert = new DonkeyInsert();
connection = createConnection(driver, url, username, password);
int numRowsInserted = donkeyInsert.insertPins(connection, DEFAULT__RECORD_COUNT);
System.out.println(String.format("# pins inserted: %d", numRowsInserted));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(connection);
}
}
private static final String INSERT_SQL = "INSERT INTO login(pin) VALUES(?) ";
public int insertPins(Connection connection, int count) {
int numInserted = 0;
if (count > 0) {
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(INSERT_SQL);
for (int i = 0; i < count; ++i) {
ps.setString(1, this.createRandomPin());
ps.addBatch();
}
int [] counts = ps.executeBatch();
for (int rowCount : counts) {
numInserted += rowCount;
}
} catch (SQLException e) {
throw new RuntimeException("SQL exception caught while inserting pins", e);
} finally {
close(ps);
}
}
return numInserted;
}
public String createRandomPin() {
// Changed it a bit. Didn't understand your requirement.
int k = this.random.nextInt(Integer.MAX_VALUE);
return Integer.toString(k);
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0)) {
return DriverManager.getConnection(url);
} else {
return DriverManager.getConnection(url, username, password);
}
}
public static void close(Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Statement st) {
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Related

Glassfish Closing JDBC Connection

I am new to Glassfish and Java EE, and I try to develop a project using glassfish as the server. The problem I have is that sometiems glassfish takes too long to deploy the project because it is closing JDBC Connections, and that takes too long.
SEVERE: Closing JDBC Connection 0
SEVERE: Closing JDBC Connection 1
SEVERE: Closing JDBC Connection 2
SEVERE: Closing JDBC Connection 3
SEVERE: Closing JDBC Connection 4
...........
SEVERE: Closing JDBC Connection 19
I don't know if the problem is from the glassfish server or from my code.. I am closing the connections after using them..
Can you please help me with figuring out where the problem comes from and how can I solve it?
I will add some more info.
I am using GlassFish Server 4.1 and Java EE 7 Web.
For connections, I have the following classes:
public class PooledConnection {
private Connection connection = null;
private boolean inuse = false;
// Constructor that takes the passed in JDBC Connection
// and stores it in the connection attribute.
public PooledConnection(Connection value) {
if (value != null) {
this.connection = value;
}
}
// Returns a reference to the JDBC Connection
public Connection getConnection() {
// get the JDBC Connection
return this.connection;
}
// Set the status of the PooledConnection.
public void setInUse(boolean value) {
inuse = value;
}
//Returns the current status of the PooledConnection.
public boolean inUse() {
return inuse;
}
// Close the real JDBC Connection
public void close() {
try {
connection.close();
} catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
}
}
The ConnectionPool class
public class ConnectionPool {
// JDBC Driver Name
private String driver = null;
// URL of database
private String url = null;
// Initial number of connections.
private int size = 0;
// Username
private String username = null;
// Password
private String password = null;
// Vector of JDBC Connections
private ArrayList<PooledConnection> pool = null;
private ArrayList<PooledConnection> poolInUse = null;
private ArrayList<PooledConnection> poolNotInUse = null;
public ConnectionPool() {
}
// Set the value of the JDBC Driver
public void setDriver(String value) {
if (value != null) {
driver = value;
}
}
// Get the value of the JDBC Driver
public String getDriver() {
return driver;
}
// Set the URL Pointing to the Datasource
public void setURL(String value) {
if (value != null) {
url = value;
}
}
// Get the URL Pointing to the Datasource
public String getURL() {
return url;
}
// Set the initial number of connections
public void setSize(int value) {
if (value > 1) {
size = value;
}
}
// Get the initial number of connections
public int getSize() {
return size;
}
// Set the username
public void setUsername(String value) {
if (value != null) {
username = value;
}
}
// Get the username
public String getUserName() {
return username;
}
// Set the password
public void setPassword(String value) {
if (value != null) {
password = value;
}
}
// Get the password
public String getPassword() {
return password;
}
// Creates and returns a connection
private Connection createConnection() throws Exception {
Connection con = null;
// Create a Connection
con = DriverManager.getConnection(url, username, password);
return con;
}
// Initialize the pool
public synchronized void initializePool() throws Exception {
// Check our initial values
if (driver == null) {
throw new Exception("No Driver Name Specified!");
}
if (url == null) {
throw new Exception("No URL Specified!");
}
if (size < 1) {
throw new Exception("Pool size is less than 1!");
}
// Create the Connections
try {
// Load the Driver class file
Class.forName(driver);
// Create Connections based on the size member
for (int x = 0; x < size; x++) {
System.err.println("Opening JDBC Connection " + x);
Connection con = createConnection();
if (con != null) {
// Create a PooledConnection to encapsulate the real JDBC Connection
PooledConnection pcon = new PooledConnection(con);
// Add the Connection to the pool
addConnection(pcon);
}
}
} catch (SQLException sqle) {
System.err.println(sqle.getMessage());
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
// Adds the PooledConnection to the pool
private void addConnection(PooledConnection value) {
// If the pool is null, create a new vector with the initial size of
if(pool == null)
{
pool = new ArrayList<PooledConnection>(size);
}
pool.add(value);
}
public synchronized void releaseConnection(Connection con)
{
if(con != null)
{
// find the PooledConnection Object
for (int x = 0; x < pool.size(); x++) {
PooledConnection pcon = pool.get(x);
// Check for correct Connection
if (pcon.getConnection() == con) {
System.err.println("Releasing Connection " + x);
// Set its inuse attribute to false, which
// releases it for use
pcon.setInUse(false);
break;
}
}
}
}
// Find an available connection
public synchronized Connection getConnection() throws Exception {
PooledConnection pcon = null;
// find a connection not in use
for (int x = 0; x < pool.size(); x++) {
pcon = pool.get(x);
// Check to see if the Connection is in use
if (pcon.inUse() == false) {
// Mark it as in use
pcon.setInUse(true);
// return the JDBC Connection stored in the
// PooledConnection object
return pcon.getConnection();
}
}
// Could not find a free connection, create and add a new one
try {
// Create a new JDBC Connection
Connection con = createConnection();
// Create a new PooledConnection, passing it the JDBC Connection
pcon = new PooledConnection(con);
// Mark the connection as in use
pcon.setInUse(true);
// Add the new PooledConnection object to the pool
pool.add(pcon);
} catch (Exception e) {
System.err.println(e.getMessage());
}
// return the new Connection
return pcon.getConnection();
}
// When shutting down the pool, you need to first empty it.
public synchronized void emptyPool() {
// Iterate over the entire pool closing the JDBC Connections.
for (int x = 0; x < pool.size(); x++) {
System.err.println("Closing JDBC Connection " + x);
PooledConnection pcon = pool.get(x);
// If the PooledConnection is not in use, close it
if (pcon.inUse() == false) {
pcon.close();
} else {
// If it is still in use, sleep for 30 seconds and force close.
try {
java.lang.Thread.sleep(30000);
pcon.close();
} catch (InterruptedException ie) {
System.err.println(ie.getMessage());
}
}
}
}
}
And the DBAccessController
public final class DBAccessController {
private Connection connection = null;
public DBAccessController(String url, String userId, String password, boolean typereadonly) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
connection = DriverManager.getConnection(url, userId, password);
connection.setReadOnly(typereadonly);
} catch (java.lang.ClassNotFoundException exceptionClassNotFound) {
} catch (java.lang.InstantiationException instantException) {
} catch (java.lang.IllegalAccessException illegalAccess) {
} catch (java.sql.SQLException sqle) {
}
}
public DBAccessController(Connection con) {
if (con != null) {
this.connection = con;
}
}
public final synchronized ArrayList runSQL(String queryString, List<String> parametrii) {
try {
PreparedStatement prepStmt = connection.prepareStatement(queryString, PreparedStatement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(true);
for (int i = 0; i < parametrii.size(); i++) {
prepStmt.setString((i + 1), parametrii.get(i));
}
ResultSet rs = prepStmt.executeQuery();
boolean flag = prepStmt.execute();
ArrayList<HashMap<String, String>> rezultate = new ArrayList<>();
ResultSet keyset = prepStmt.getGeneratedKeys();
while (keyset != null && keyset.next()) {
HashMap<String, String> keysHM = new HashMap<>();
// Retrieve the auto generated key(s).
int key = keyset.getInt(1);
keysHM.put("cheia", Integer.toString(key));
rezultate.add(keysHM);
}
if (flag) {
ResultSet res = prepStmt.getResultSet();
ResultSetMetaData rsmd = res.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
while (res.next()) {
HashMap<String, String> hm = new HashMap<>();
Object o = res.getObject(i);
if (o != null) {
hm.put(rsmd.getColumnName(i), o.toString());
}
}
rezultate.add(hm);
}
res.close();
prepStmt.close();
return rezultate;
} else {
prepStmt.close();
if (keyset != null) {
return rezultate;
} else {
return null;
}
}
} catch (java.sql.SQLException sqle) {
return null;
}
}
public final synchronized ArrayList runSQL(String queryString) {
try {
PreparedStatement statement = connection.prepareStatement(queryString, PreparedStatement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(true);
boolean flag = statement.execute();
System.out.println("Statement: " + statement + " flag: " + flag);
ArrayList<HashMap<String, String>> rezultate = new ArrayList<>();
ResultSet keyset = statement.getGeneratedKeys();
while (keyset != null && keyset.next()) {
HashMap<String, String> keysHM = new HashMap<>();
// Retrieve the auto generated key(s).
int key = keyset.getInt(1);
keysHM.put("cheia", Integer.toString(key));
rezultate.add(keysHM);
System.out.println("Cheile " + keyset.toString());
}
System.out.println("Cheile " + keyset.toString());
if (flag) {
ResultSet res = statement.getResultSet();
ResultSetMetaData rsmd = res.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
System.out.println("res: " + res + " rsmd: " + rsmd + " numberOfColumns: " + numberOfColumns);
while (res.next()) {
HashMap<String, String> hm = new HashMap<>();
System.out.println("Res to string " + res.toString());
for (int i = 1; i <= numberOfColumns; i++) {
System.out.println("obiectul " + i + " res.getObject(i) " + res.getObject(i));
Object o = res.getObject(i);
System.out.println("rsmd.getColumnName(i) " + rsmd.getColumnName(i));
if (o != null) {
hm.put(rsmd.getColumnName(i), o.toString());
}
}
rezultate.add(hm);
}
res.close();
statement.close();
System.out.println("Return rezultate");
return rezultate;
} else {
System.out.println("Return null 1");
statement.close();
if (keyset != null) {
return rezultate;
} else {
return null;
}
}
} catch (java.sql.SQLException sqle) {
System.out.println("Return null 2" + sqle.getMessage());
return null;
}
}
public final void stop() {
try {
connection.close();
} catch (java.sql.SQLException e) {
}
}
}
When I need to use a connection I do the following (for example):
Connection con;
try {
con = cp.getConnection();
udao = new UtilizatorDAO(con);
con.close();
}
} catch (Exception ex) {
Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
}
out.close();

servlet mysql Runtime Exception [duplicate]

This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 7 years ago.
java.sql.SQLException: Parameter index out of range (1 > number of parameters,
which is 0)
For the following code, what kind of parameter change is required to make the code run?
package com.chen.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class SqlHelper {
private static Connection conn = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;
private static String url = "jdbc:mysql://localhost:3306/userdata";
private static String username1 = "root";
private static String password1 = "root";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public static Connection getConnection() {
try {
conn = DriverManager.getConnection(url, username1, password1);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void executeUpdate(String sql, String[] parameters) {
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
if (parameters != null) {
for (int i = 0; i < parameters.length; i++) {
ps.setString(i+1 , parameters[i]);
}
}
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
close(rs,ps,conn);
}
}
public static ResultSet executeQuery(String sql,String[]parameters){
try{
conn=getConnection();
ps=conn.prepareStatement(sql);
if(parameters!=null&&!parameters.equals("")){
for(int i=0;i<parameters.length;i++){
ps.setString(i+1,parameters[i]);
}
}
rs=ps.executeQuery();
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}finally{
//close(rs,ps,conn);
}
return rs;
}
public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
ps = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public static Connection getConn() {
return conn;
}
public static PreparedStatement getPs() {
return ps;
}
public static ResultSet getRs() {
return rs;
}
}
Below is the error stack:
//java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:904)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3797)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3779)
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4600)
at com.chen.util.SqlHelper.executeQuery(SqlHelper.java:100)
at com.chen.services.UserService.checkUser(UserService.java:22)
at com.chen.controller.ControllerServlet.doGet(ControllerServlet.java:33)
at
package com.chen.services;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.chen.domain.User;
import com.chen.util.SqlHelper;
public class UserService {
// 用checkUser()来判断用户是否存在
public boolean checkUser(User user) {
boolean b = false;
// 使用SqlHelper来完成查询任务
String sql = "select * from user where username=? and password=?";
String parameters[] = { user.getUsername(), user.getPassowrd() };
ResultSet rs = SqlHelper.executeQuery("sql", parameters);
// 根据rs来判断该用户是否存在
try {
if (rs.next()) {
b = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return b;
}
public ArrayList getUserByPage(int pageNow, int pageSize) {
ArrayList<User> arr = new ArrayList<User>();
// 查询sql
//String sql = "select * from user where id>3 order by id limit 20";
String sql="select sql_calc_found_rows * from user limit 0,10";
ResultSet rs = SqlHelper.executeQuery(sql, null);
// 二次封装 把 ResultSet -->User对象-->Arraylist(集合)
try {
while (rs.next()) {
User u = new User();
try {
u.setId(rs.getInt(1));
u.setUsername(rs.getString(2));
u.setPassowrd(rs.getString(3));
// 一定记住 u-->ArrayList
arr.add(u);
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return arr;
}
public int getPageCount(int pageSize) {
String sql = "select * from user";
int rowCount = 0;
ResultSet rs = SqlHelper.executeQuery(sql, null);
try {
rs.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rowCount = rs.getInt(1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return (rowCount - 1) / pageSize + 1;
}
//删除用户
public boolean deleUser(String id){
boolean b=true;
String sql="delete from user where id=?";
String parameters[]={id};;
try {
SqlHelper.executeUpdate(sql, parameters);
} catch (Exception e) {
b=false;
}
return b;
}
//用过id获取用户数据
public User getUserById(String id){
User user=new User();
String sql="select * from user where id= ?";
String parameters[]={id};
ResultSet rs=SqlHelper.executeQuery(sql, parameters);
try {
if(rs.next()){
user.setId(rs.getInt(1));
user.setUsername(rs.getString(2));
user.setPassowrd(rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return user;
}
//修改用户
public boolean updateUser(User user){
boolean b=true;
String sql="update user set username=?,password=? where id=?";
String parameters[]={user.getUsername(),user.getPassowrd(),user.getId()+""};
try {
SqlHelper.executeUpdate(sql, parameters);
} catch (Exception e) {
b=false;
}
return b;
}
}
Replace this:
ResultSet rs = SqlHelper.executeQuery("sql", parameters);
With:
ResultSet rs = SqlHelper.executeQuery(sql, parameters);

Deferencing Null pointer

public class Model
{
public static Connection getConnection()
{
Connection conn = null;
try
{
Class.forName("oracle.jdbc.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "System", "system");
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
return conn;
}
public static class Cart
{
public String itmName="";
public int howmany=0;
public static long itmQty=0, itmID=0;
public double itmPrice=0.0, itmCost=0.0, totalSum=0.0;
}
public static ArrayList<Cart> getCartDatabase(String user) throws Exception
{
Connection conn = getConnection();
String sql = "select * from userCarts where userID = '" + user + "'";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rst = pstmt.executeQuery();
ArrayList<Cart> al = null;
Cart crt=null;
while(rst.next())
{
System.out.println("CPoint");
try
{
long p = rst.getLong("itemID");
crt.itmID = p; // This is the line thats creating the error
System.out.println(p + " is long! I guess...");
}
catch(NullPointerException e)
{
System.out.println("NPE Caught in Model");
}
System.out.println("CP 1 " + crt.itmID);
ArrayList<row> alr=null;
try
{
alr = Model.getStoreInventory();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("CP 2");
for(int i=0; i<alr.size(); i++)
{
crt.itmName = alr.get(i).itmName;
crt.itmPrice = alr.get(i).itmPrice;
crt.itmQty = alr.get(i).itmQty;
}
System.out.println("CP 3");
crt.howmany = rst.getInt("howmany");
crt.itmCost = crt.itmPrice*crt.howmany;
al.add(crt);
}
return al;
}
}
When I try to access this method of getCartFromDatabase, it gives a NullPointerException however I don't understand why it would do this. Moreover, I tried to make the class as a non static class too, but still it gave the same error:
"Possible deferencing Null Pointer"
Cart crt=null;
while(rst.next())
{
System.out.println("CPoint");
try
{
long p = rst.getLong("itemID");
crt.itmID = p; // This is the line thats creating the error
System.out.println(p + " is long! I guess...");
}
crt is null when you try to access crt.itemID. You have to assign it an instance first.
I think you may simply change the first line from the snippet to
Cart crt = new Cart();

generating id for a row

i have called the return values nextId on a button click event but whenever i am trying to execute the button click event it initialses it to start and then it generates next can you please help me with this??
package util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CalendarUtil {
private static String buffer = "";
private static int counter = 1;
public String nextID() {
final String datePrefix = new SimpleDateFormat("yyyyMMdd").format(new Date());
if (Long.parseLong(returnMaxId()) > 0) {
CalendarUtil.counter = Integer.parseInt(returnMaxId().substring(8, returnMaxId().length()));
}
if (buffer.equals(datePrefix)) {
CalendarUtil.counter++;
} else {
CalendarUtil.buffer = datePrefix;
CalendarUtil.counter = 1;
}
String suffix = "";
if (CalendarUtil.counter <= 1000) {
if (validateRange(0, 9, CalendarUtil.counter)) {
suffix += "00" + counter;
} else if (validateRange(10, 99, CalendarUtil.counter)) {
suffix += "0" + counter;
} else if (validateRange(99, 999, CalendarUtil.counter)) {
suffix += counter;
}
}
return (datePrefix + suffix);
}
public boolean validateRange(int min, int max, int field) {
return field >= min && field <= max;
}
public String returnMaxId() {
String result = "";
try {
DBUtil util = new DBUtil();
Connection connection = util.getConnection();
ResultSet rs = connection.createStatement().executeQuery("SELECT MAX(id) AS 'lastId' FROM crap ");
if (rs.next()) {
result = (rs.getString(1) != null) ? rs.getString(1) : "0";
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error : " + e.getMessage());
}
return result;
}
public static void main(String[] args) {
}
}
result = (rs.getString(1) != null) ? rs.getString(1) : "0";
should be
result = (rs.getInt(1) != null) ? rs.getInt(1) : "0";
however you should be using JDBC API methods to get last inserted id, checkout the below code.
pstmt = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);
pstmt.executeUpdate();
ResultSet keys = pstmt.getGeneratedKeys();
keys.next();
key = keys.getInt(1); // gets the last inserted id
keys.close();
pstmt.close();
conn.close();
} catch (Exception e) { e.printStackTrace(); }
return key;
}

Why is java.sql.DriverManager.getConnection(...) hanging?

I am attempting to get a connection to my University's MySQL DB but the connection is hanging.
import java.sql.*;
public class ConnectToDB {
public static void main(String args[]){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://db.cs.myUniversity.com/dbName";
System.out.println("BEFORE");
Connection con = DriverManager.getConnection(url,"me", "password");
System.out.println("AFTER");
...
This call: time java ConnectToDB prints (after I eventually kill it):
Copyright 2004, R.G.Baldwin
BEFORE
AFTER
real 3m9.343s
user 0m0.316s
sys 0m0.027s
I just downloaded MySQL Connector/J from here. I am not sure if that is part of the problem. I followed the directions fairly precisely.
I can also connect to mysql on the command line like this:
$ mysql -u me -h db.cs.myUniversity.com -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 882328
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use dbName;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SHOW tables;
+-------------------+
| Tables_in_dbName |
+-------------------+
| classics |
+-------------------+
1 row in set (0.00 sec)
Possible Problems:
The Java code I wrote
How I installed MySQL Connector/J
Some kind of network problem blocking the connection
Question: What should I do to solve this problem? Why is the getConnection call hanging?
I was following this tutorial
The output you provide is not helpful.
I see BEFORE and AFTER being printed, so the connection was made. The code doesn't show what those timings encompass, so I can't tell what they mean.
If you're suggesting that your code had to killed because the connection was never made, it's probably because your username, password, and client IP have not been GRANTed permissions that are needed.
Could be:
your university network; find a network engineer to ask about firewalls.
permission in the MySQL database; find the DBA and ask.
your code; you didn't post enough to tell. Post the whole class.
What's up with that copyright? I'd lose that.
This code works. Modify it so the pertinent parameters match your problem. (Mine uses MySQL 5.1.51 and a table named Party.) When I run it on my local machine, I get a wall time of 641 ms.
package persistence;
import java.sql.*;
import java.util.*;
/**
* DatabaseUtils
* User: Michael
* Date: Aug 17, 2010
* Time: 7:58:02 PM
*/
public class DatabaseUtils
{
/*
private static final String DEFAULT_DRIVER = "org.postgresql.Driver";
private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/party";
private static final String DEFAULT_USERNAME = "pgsuper";
private static final String DEFAULT_PASSWORD = "pgsuper";
*/
private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
private static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/party";
private static final String DEFAULT_USERNAME = "party";
private static final String DEFAULT_PASSWORD = "party";
public static void main(String[] args)
{
long begTime = System.currentTimeMillis();
String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER);
String url = ((args.length > 1) ? args[1] : DEFAULT_URL);
String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME);
String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD);
Connection connection = null;
try
{
connection = createConnection(driver, url, username, password);
DatabaseMetaData meta = connection.getMetaData();
System.out.println(meta.getDatabaseProductName());
System.out.println(meta.getDatabaseProductVersion());
String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON ORDER BY LAST_NAME";
System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
connection.setAutoCommit(false);
String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)";
List parameters = Arrays.asList( "Foo", "Bar" );
int numRowsUpdated = update(connection, sqlUpdate, parameters);
connection.commit();
System.out.println("# rows inserted: " + numRowsUpdated);
System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
}
catch (Exception e)
{
rollback(connection);
e.printStackTrace();
}
finally
{
close(connection);
long endTime = System.currentTimeMillis();
System.out.println("wall time: " + (endTime - begTime) + " ms");
}
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Class.forName(driver);
if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0))
{
return DriverManager.getConnection(url);
}
else
{
return DriverManager.getConnection(url, username, password);
}
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement st)
{
try
{
if (st != null)
{
st.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet rs)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static List<Map<String, Object>> map(ResultSet rs) throws SQLException
{
List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
try
{
if (rs != null)
{
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
while (rs.next())
{
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 1; i <= numColumns; ++i)
{
String name = meta.getColumnName(i);
Object value = rs.getObject(i);
row.put(name, value);
}
results.add(row);
}
}
}
finally
{
close(rs);
}
return results;
}
public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters) throws SQLException
{
List<Map<String, Object>> results = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = connection.prepareStatement(sql);
int i = 0;
for (Object parameter : parameters)
{
ps.setObject(++i, parameter);
}
rs = ps.executeQuery();
results = map(rs);
}
finally
{
close(rs);
close(ps);
}
return results;
}
public static int update(Connection connection, String sql, List<Object> parameters) throws SQLException
{
int numRowsUpdated = 0;
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement(sql);
int i = 0;
for (Object parameter : parameters)
{
ps.setObject(++i, parameter);
}
numRowsUpdated = ps.executeUpdate();
}
finally
{
close(ps);
}
return numRowsUpdated;
}
}

Categories