This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed last month.
public class ReportView extends JFrame {
Connection con=null;
void showReport() throws SQLException, ClassNotFoundException, JRException {
con=DriverManager.getConnection("jdbc:postgresql://localhost:5432/Test");
JasperReport report=JasperCompileManager.compileReport("Testing.jrxml");
JasperPrint print=JasperFillManager.fillReport(report,null,con);
JRViewer viewer=new JRViewer(print);
viewer.setOpaque(true);
viewer.setVisible(true);
this.add(viewer);
this.setSize(300, 200);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
This is error:
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost:5432/Test
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
What is the wrong?
You'll need to load the driver somewhere. Class.forName("org.postgresql.Driver");
You'll need the postgresql driver .jar file in the classpath of your program.
You need to put the postgreSQL JDBC driver on your classpath.
See the official documentation for instructions.
I don't know, but this worked perfectly for me. I'm running JDK 1.6.0_21 from Sun and PostgreSQL 8.1 locally:
package persistence;
import java.sql.*;
import java.util.*;
/**
* 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;
}
}
And here's the result:
PostgreSQL
8.1.3
before insert: [{first_name=Foo, person_id=55, last_name=Bar}, {first_name=Foo, person_id=52, last_name=Bar}, {first_name=Foo, person_id=53, last_name=Bar}, {first_name=Foo, person_id=54, last_name=Bar}, {first_name=Foo, person_id=56, last_name=Bar}, {first_name=SEAMUS, person_id=2, last_name=DUFFY}, {first_name=MICHAEL, person_id=1, last_name=DUFFY}]
# rows inserted: 1
after insert: [{first_name=Foo, person_id=56, last_name=Bar}, {first_name=Foo, person_id=52, last_name=Bar}, {first_name=Foo, person_id=53, last_name=Bar}, {first_name=Foo, person_id=54, last_name=Bar}, {first_name=Foo, person_id=55, last_name=Bar}, {first_name=Foo, person_id=57, last_name=Bar}, {first_name=SEAMUS, person_id=2, last_name=DUFFY}, {first_name=MICHAEL, person_id=1, last_name=DUFFY}]
wall time: 344 ms
Related
This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed last month.
public class ReportView extends JFrame {
Connection con=null;
void showReport() throws SQLException, ClassNotFoundException, JRException {
con=DriverManager.getConnection("jdbc:postgresql://localhost:5432/Test");
JasperReport report=JasperCompileManager.compileReport("Testing.jrxml");
JasperPrint print=JasperFillManager.fillReport(report,null,con);
JRViewer viewer=new JRViewer(print);
viewer.setOpaque(true);
viewer.setVisible(true);
this.add(viewer);
this.setSize(300, 200);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
This is error:
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost:5432/Test
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
What is the wrong?
You'll need to load the driver somewhere. Class.forName("org.postgresql.Driver");
You'll need the postgresql driver .jar file in the classpath of your program.
You need to put the postgreSQL JDBC driver on your classpath.
See the official documentation for instructions.
I don't know, but this worked perfectly for me. I'm running JDK 1.6.0_21 from Sun and PostgreSQL 8.1 locally:
package persistence;
import java.sql.*;
import java.util.*;
/**
* 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;
}
}
And here's the result:
PostgreSQL
8.1.3
before insert: [{first_name=Foo, person_id=55, last_name=Bar}, {first_name=Foo, person_id=52, last_name=Bar}, {first_name=Foo, person_id=53, last_name=Bar}, {first_name=Foo, person_id=54, last_name=Bar}, {first_name=Foo, person_id=56, last_name=Bar}, {first_name=SEAMUS, person_id=2, last_name=DUFFY}, {first_name=MICHAEL, person_id=1, last_name=DUFFY}]
# rows inserted: 1
after insert: [{first_name=Foo, person_id=56, last_name=Bar}, {first_name=Foo, person_id=52, last_name=Bar}, {first_name=Foo, person_id=53, last_name=Bar}, {first_name=Foo, person_id=54, last_name=Bar}, {first_name=Foo, person_id=55, last_name=Bar}, {first_name=Foo, person_id=57, last_name=Bar}, {first_name=SEAMUS, person_id=2, last_name=DUFFY}, {first_name=MICHAEL, person_id=1, last_name=DUFFY}]
wall time: 344 ms
My DBCP configuration keeps creating new connections, so much that my MySQL server blocks it because of too many connections:
public class SQL {
private final static String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
private final static String USERNAME = "secret";
private final static String PASSWORD = "secret";
private final static String URL = "secret";
public static Connection getConnection() {
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName(DRIVER_CLASS_NAME);
basicDataSource.setUrl(URL);
basicDataSource.setUsername(USERNAME);
basicDataSource.setPassword(PASSWORD);
try {
return basicDataSource.getConnection();
} catch (SQLException ex) {
Logger.getLogger(SQL.class.getName()).log(Level.SEVERE, null, ex);
throw new IllegalStateException("bf4.sql.SQL.getConnection: No connection could be made: " + ex.getMessage());
}
}
}
My xxxManager.java:
public class PlayerkillManager extends Manager<PlayerkillBean, PlayerkillConstraint> {
public PlayerkillManager() {
super(SQL.getConnection());
}
#Override
protected PreparedStatement insertPS(final PlayerkillBean playerkill) throws SQLException {
PreparedStatement ps = connection.prepareStatement("INSERT INTO playerkills (`date`, `playerId`, `targetId`, `weaponId`, `headshot`) VALUES(?, ?, ?, ?, ?)", PreparedStatement.RETURN_GENERATED_KEYS);
ps.setObject(1, playerkill.getDate());
ps.setObject(2, playerkill.getPlayerId());
ps.setObject(3, playerkill.getTargetId());
ps.setObject(4, playerkill.getWeaponId());
ps.setObject(5, playerkill.getHeadshot());
return ps;
}
#Override
protected PreparedStatement updatePS(final PlayerkillBean playerkill) throws SQLException {
throw new UnsupportedOperationException("There are no non-key columns in this table.");
}
#Override
protected PreparedStatement deletePS(final PlayerkillBean playerkill) throws SQLException {
PreparedStatement ps = connection.prepareStatement("DELETE FROM playerkills WHERE `id` = ? AND `date` = ? AND `playerId` = ? AND `targetId` = ? AND `weaponId` = ? AND `headshot` = ?");
ps.setObject(1, playerkill.getId());
ps.setObject(2, playerkill.getDate());
ps.setObject(3, playerkill.getPlayerId());
ps.setObject(4, playerkill.getTargetId());
ps.setObject(5, playerkill.getWeaponId());
ps.setObject(6, playerkill.getHeadshot());
return ps;
}
#Override
protected String searchQuery() {
return "SELECT `playerkills`.`id`, `playerkills`.`date`, `playerkills`.`playerId`, `playerkills`.`targetId`, `playerkills`.`weaponId`, `playerkills`.`headshot` FROM playerkills";
}
#Override
protected String tableName() {
return "playerkills";
}
#Override
protected String[] columnNames() {
return new String[] {
"id",
"date",
"playerId",
"targetId",
"weaponId",
"headshot",
};
}
#Override
protected Map<TableField, List<List<TableField>>> getPaths() {
//Function not interesting and too much code
}
#Override
protected PlayerkillBean createBean(final ResultSet rs) throws SQLException {
return new PlayerkillBean(rs);
}
}
Manager.java class:
public abstract class Manager<B extends Bean, C extends AbstractConstraint> implements Closeable {
protected final Connection connection;
public Manager(final Connection con) {
this.connection = con;
}
public final int insert(final B b) throws InsertException {
try {
try (PreparedStatement ps = insertPS(b)) {
ps.executeUpdate();
try (ResultSet rs = ps.getGeneratedKeys()) {
rs.last();
if (rs.getRow() != 0) {
rs.beforeFirst();
rs.next();
return rs.getInt(1);
}
else {
return -1;
}
}
}
} catch (SQLException ex) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
throw new InsertException(ex);
}
}
public final boolean update(final B b) throws UpdateException {
try {
try (PreparedStatement ps = updatePS(b)) {
return ps.execute();
}
} catch (SQLException ex) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
throw new UpdateException(ex);
}
}
public final boolean delete(final B b) throws DeleteException {
try {
try (PreparedStatement ps = deletePS(b)) {
return ps.execute();
}
} catch (SQLException ex) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
throw new DeleteException(ex);
}
}
public final B get(final AbstractConstraint... c) throws SearchException {
List<B> beans = search(c);
if (beans.size() == 1) {
return beans.get(0);
}
throw new IllegalArgumentException("orm.Manager.get: beans.size() != 1: beans.size() = " + beans.size());
}
public final List<B> search(final AbstractConstraint... c) throws SearchException {
if (c.length == 0) {
throw new IllegalArgumentException("orm.Manager.search: c.length == 0");
}
try {
List<B> beans = new ArrayList<>();
for (AbstractConstraint constraint : c) {
try (PreparedStatement ps = new QueryBuilder(connection, tableName(), getPaths(), searchQuery()).add(constraint).build();
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
beans.add(createBean(rs));
}
}
}
if (c.length > 1) {
boolean sorting = true;
Field field = c[0].getField();
Order order = c[0].getOrder();
for (int i = 1; i < c.length; i++) {
Field currentField = c[i].getField();
Order currentOrder = c[i].getOrder();
if (!field.equals(currentField) || !order.equals(currentOrder)) {
sorting = false;
break;
}
}
if (sorting) {
//sort on field with comparator of supertype
}
}
return beans;
} catch (SQLException ex) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
throw new SearchException(ex);
}
}
public final List<B> getAll() throws SearchException {
return getAll(Order.NONE, null);
}
public final List<B> getAll(final Order order, final Field field) throws SearchException {
try {
List<B> beans = new ArrayList<>();
try (
PreparedStatement ps = connection.prepareStatement(searchQuery() + " " + orderQuery(order, field));
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
beans.add(createBean(rs));
}
}
return beans;
} catch (SQLException ex) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
throw new SearchException(ex);
}
}
public final int getRowCount(final AbstractConstraint... c) throws SearchException {
return search(c).size();
}
#Override
public void close() {
//was uncommented?
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
}
}
private String orderQuery(final Order order, final Field field) {
if (order == Order.NONE) {
return "";
}
return "ORDER BY " + field.getFieldName() + " " + order.getOrdername();
}
abstract protected PreparedStatement insertPS(B b) throws SQLException;
abstract protected PreparedStatement updatePS(B b) throws SQLException;
abstract protected PreparedStatement deletePS(B b) throws SQLException;
abstract protected String searchQuery();
abstract protected String tableName();
abstract protected String[] columnNames();
abstract protected Map<TableField, List<List<TableField>>> getPaths();
abstract protected B createBean(ResultSet rs) throws SQLException;
}
Some statistics I have gathered:
Max concurrent connections: 152
Failed connections: 12
Aborted connections: 375
Total connections: 844
Number of insert queries: 373
I would have expected that 1 connection would have been used though, what is going wrong?
EDIT: To clarify, my code calls the xxxManager for example like this: playerkillManager.insert(new PlayerkillBean(...));
You are creating a new connection pool every time you call SQL.getConnection() which is not how connection pools should be used.
You should share a single javax.sql.DataSource (doc) around your application, not individual connections.
So, maybe you could change your code to:
public class SQL {
private final static String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
private final static String USERNAME = "secret";
private final static String PASSWORD = "secret";
private final static String URL = "secret";
private final static DataSource dataSource;
static {
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName(DRIVER_CLASS_NAME);
basicDataSource.setUrl(URL);
basicDataSource.setUsername(USERNAME);
basicDataSource.setPassword(PASSWORD);
dataSource = basicDataSource;
}
public static DataSource getDataSource() {
return dataSource;
}
}
Then in the rest of your classes, you can use that data source. Important things to remember are that DataSource.getConnection() borrows a connection from the pool and Connection.close() does not actually close the connection; calling close() returns the connection to the pool. If you fail to call Connection.close() on a borrowed connection you have a connection leak.
Your current code will need editing to use try-with-resources when borrowing the connection e.g.
public void foo() {
try (Connection conn = datasource.getConnection()) {
//your code here
} catch (SQLException e) {
e.printStackTrace();
}
}
I've ran into a problem of having to run a number of different queries on the DB (different return types, different number of columns, etc).
While writing that i started to wonder if there's a proper way of writing a helper function.
It seemed that it's really easy to write a function that returns a ResultSet.
However since it a) doesn't close connection b) doesn't close the result set it seems as a possibly working, but improper solution. Is there any place to dump in all results so that they can be returned safely.
(Only thing i could come up with, is just returning a 2D string array (after converting all data to strings) and then converting it all back)
EDIT : Sorry for not writing clear, was wondering if there's any way to just store the result of the query as is (don't need to modify it) without writing a separate method for every possible return type.
The idea behind a 2d string list is being able to store the query values as is.
Col1 Row1 | Col2 Row1 | Col3 Row1
Col1 Row2 | Col2 Row2 | Col3 Row2
EDIT 2 Thank you for replies, i guess i'll just write a small parser for it.
You shouldn't be returning resultSets, you should read the results from the resultset into some kind of container object. A ResultSet is a wrapper around a database cursor, it goes away when the connection closes. It's something you read from and close right away, not something you can pass around your application.
Look at how spring-jdbc does it. You implement a resultSetMapper that is passed to the method on the JdbcTemplate.
Several observations:
You don't need to use Spring to use spring-jdbc. However, I see very little value in reimplementing this stuff yourself.
It's not the job of the code that reads the ResultSet to open and close connections, that needs to be elsewhere.
I'd recommend looking at Spring JDBC. Don't write such a thing yourself. It's already been done, and quite well.
For example, I don't like your idea of returning a List of Strings. You lose a lot of info that way. I'd return a Map of Lists (column view) or List of Maps (row view).
If you must, here are some database utilities that would get you started.
package persistence;
import java.sql.*;
import java.util.*;
/**
* util.DatabaseUtils
* User: Michael
* Date: Aug 17, 2010
* Time: 7:58:02 PM
*/
public class DatabaseUtils {
/*
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DEFAULT_URL = "jdbc:oracle:thin:#host:1521:database";
private static final String DEFAULT_USERNAME = "username";
private static final String DEFAULT_PASSWORD = "password";
*/
/*
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;
}
}
You can write helper functions that parse a ResultSet and convert it into an ArrayList or an array or even the fields of an object. For instance, lets say you have a table of orders and then a query returns all of the rows of that table for a particular user (customer). We could then do something like this:
static List<Order> parseOrder(ResultSet rs) {
ArrayList<Order> orderList = new ArrayList<>();
while(rs.next() ) {
Order order = new Order();
order.setID(rs.getInt(1));
order.setCustomerID(rs.getInt(2));
order.setItemName(rs.getString(3));
orderList.add(order);
}
return orderList;
}
Simply turning the result set into an array of an array of Objects would be more general, but probably less useful.
I would leave it up to the calling function to close this ResultSet and possible the PreparedStatement (or Statement) and database connection.
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;
}
}
I am trying to insert some rows in to a table... I am using postgressql-7.2.jar.
I get the following exception
org.postgresql.util.PSQLException: No results were returned by the query.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:255)
I have already Googled and the possible reasons suggested are
Use executeUpdate() method or execute() method instead of executeQuery() method.
This could possibly be because of jar problem; try other versions of postgres jars.
In some places they save it could be because of heap space error.
I have tried all the three solutions but none of them work...
I am not pasting the code since I have just used statement.executeUpdate(queryString).
The insert statements load the data in to the table but still I get this error.
Can some one help me out in this?
What type of SQL statement are you trying to run with executeQuery()? It should not be an INSERT or UPDATE - these are not queries.
Without posting the actual SQL statement, code samples, or what the table looks like - it's pretty hard to actually help you with your problem. Without specifics all we can do is guess.
This code works perfectly for me running PostgreSQL 8.1 and its driver. Perhaps it can be a template for finding what's wrong with yours.
You need a single table named PERSON with columns PERSON_ID, FIRST_NAME, LAST_NAME. I made PERSON_ID the auto incremented primary key.
package persistence;
import java.sql.*;
import java.util.*;
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";
public static void main(String[] args)
{
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);
}
}
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;
}
}
A statement inserting rows does not return any rows back as a result, as opposed to a SELECT.