I am trying to connect to a MySQL database from a jsp page using jdbc in the backend.
I have the following code:
public static void insertIntoDatabase(String code,String name,String temp,String hum,String del) {
Connection con = null;
if (del.length() == 0) {
del="no data";
}
name = name.replaceAll("\\(.+?\\)", "");
name = name.replaceAll(" ", "_");
del = del.replaceAll(" ", "_");
System.out.println("del "+del);
String url = "jdbc:mysql://localhost:3306/test";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,"root","");
con.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS aiportdetails(code VARCHAR(50) PRIMARY KEY, " +
"name VARCHAR(250), temp VARCHAR(50), hum VARCHAR(50), del VARCHAR(50))");
ResultSet rs = con.prepareStatement("SELECT * FROM airportdetails;").executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
I am getting the following error at
ResultSet rs = con.prepareStatement("SELECT * FROM airportdetails;").executeQuery();
error:
Table 'test.airportdetails' doesn't exist
But from my phpmyadmin I can see that the table is created and exists:
What is the reason I am getting this error?
Thank you.
executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
Currently you are trying to use this for creating a table. That's the reason why you are getting that error.
Refer to the documentation Java 6 OR Java 1.4.2 for executeUpdate
EDIT:
You should create a table using Statement
Statement st = con.createStatement();
String table = "Create table .......";
st.executeUpdate(table);
you can put the initialize the connection and load driver at the constructor level, then in the method you can first createt check the table if it exists or create it then if it is successful, continue with the insert operation.like this:
public class MyBean{
String url = "jdbc:mysql://localhost:3306/test,"root","" ";
public MyBean(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url);
}catch(Exception e){
}
}
public static void insertIntoDatabase(String code,String name,String temp,String hum,String del) {
Connection con = null;
if (del.length() == 0) {
del="no data";
}
name = name.replaceAll("\\(.+?\\)", "");
name = name.replaceAll(" ", "_");
del = del.replaceAll(" ", "_");
System.out.println("del "+del);
try {
con = DriverManager.getConnection(url);
Int result = con.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS aiportdetails(code VARCHAR(50) PRIMARY KEY, " +
"name VARCHAR(250), temp VARCHAR(50), hum VARCHAR(50), del VARCHAR(50))");
if(result>0){
try{
ResultSet rs = con.prepareStatement("SELECT * FROM airportdetails;").executeQuery();
}catch(Exception e){
}finally{
}
}//end if
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
Related
I am getting the error as per the heading and am totally at a lose as to why.
public static int addSkill( String code ) {
PreparedStatement insertSkill = null;
int result = 0;
Connection connection = null;
try {
connection = database.connect(null, null);
insertSkill = connection.prepareStatement( "INSERT INTO Skill VALUES (0,?)" );
/* *Set the wild cards of the prepared statement insertSkill */
insertSkill.setString( 1, code );
result = insertSkill.executeUpdate();
} // try()
catch ( java.sql.SQLIntegrityConstraintViolationException insert ) {
// This catches a problem of inserting a duplicate skill.
// If it occurs, the method will return 0 (initial value of result).
log.errorMessage("DataStore: Exception: " + insert.getMessage());
} // catch()
catch ( SQLException sqlException ) {
log.errorMessage("DataStore: Exception: " + sqlException.getMessage());
} // catch()
finally{
if(connection !=null){
try {
connection.close();
}
catch (SQLException e) {
log.errorMessage("Connction failed to return to the pool\n");
e.printStackTrace();
}
}
}
return result;
}// addSkill()
I have a database named as "test" in which I have a table named as "first" which contains raw data, I want to get this table data. What should be the prepare statement I have to use in order to get data from table "first" ? Below is the code I am trying. Any help or guidance would be appreciable.
#Path("/database") // Specific URL
#GE
#Produces(MediaType.TEXT_PLAIN)
public String returnDB_Status() throws Exception {
PreparedStatement query = null;
String result = null;
Connection conn = null;
try {
conn = mysql_prac.dbConn().getConnection(); // this works fine ...
query = conn.prepareStatement("SELECT * from first" ); // Table named as "first" is placed inside the connected database.
ResultSet rs = query.executeQuery();
result = "Data received : " + rs;
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
return result;
}
and the source code used get a connection
public class mysql_prac {
private static DataSource mysql_prac = null;
private static Context context = null;
public static DataSource dbConn() throws Exception {
if (mysql_prac != null) {
return mysql_prac;
}
try {
if (context == null) {
context = new InitialContext();
}
mysql_prac = (DataSource) context.lookup("JDBC_ref"); //JNDI ID (JDBC_REF)
} catch (Exception e) {
e.printStackTrace();
}
return mysql_prac;
}
}
You must loop through the ResultSet to get the fields of each row. So I made the following edit together with some comments.Please notice the comments.
try {
conn = mysql_prac.dbConn().getConnection(); // this works fine ...
query = conn.prepareStatement("SELECT * from first" ); // Table named as "first" is placed inside the connected database.
ResultSet rs = query.executeQuery();//You must loop through the results set to get the fields of each row
while(rs.next()){
String dbUserID = rs.getString("column1");//this is just an example to retrieve all data in the column called 'column1'
result = "Data received : " + dbUserID;
System.out.println(result);
}
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
I am facing following exception:
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.io.EOFException.
After specifying following pool-properties for the datasource, its able to auto-reconnect on connection-time-out; but the dead connections are existing in the pool are being reused and not being killed/evicted (ie. the validation-query and eviction parameters are not working). Following is my code. Can anyone please suggest some solution how to handle this?
public class DbConnection {
static DataSource datasource = new org.apache.tomcat.jdbc.pool.DataSource();
public static Connection getConnection() {
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:mysql://192.168.0.9:3306/oet_v3?autoReconnect=true");
p.setDriverClassName("com.mysql.jdbc.Driver");
p.setUsername("root");
p.setPassword("napster123");
p.setJmxEnabled(true);
p.setTestWhileIdle(true);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(true);
p.setValidationInterval(20000);
p.setTimeBetweenEvictionRunsMillis(3000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setMinEvictableIdleTimeMillis(3000);
p.setMinIdle(10);
Connection con = null;
try {
Context ctx = new InitialContext();
((DataSourceProxy) datasource).setPoolProperties(p);
con = datasource.getConnection();
Statement st1 = con.createStatement();
ResultSet rs1 = st1.executeQuery("select * from User_Login limit 0,1");
if (rs1.next()) {
System.out.println("LIVE CONNECTION********con: " + con + " rs.next=" + rs1.next());
} else {
System.out.println("&&&&&rs is null so secnd conn: " + con);
DataSource datasource1 = new org.apache.tomcat.jdbc.pool.DataSource();
((DataSourceProxy) datasource1).setPoolProperties(p);
con = datasource1.getConnection();
return con;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
} finally {
return con;
}
finally {
System.out.println("before returning con: "+con);
if (con!=null) try {return con;}catch (Exception ignore) {}
return con;
}
}
}
I have a query
SELECT * FROM db_tabel WHERE someStringField=\'#someStringValue\'
and i know that #someStringValue exists in tabel
but MySqlDataReader object told me than query returns nothing
where is mistake?
C# code:
const string command = "SELECT * FROM `db_tabel` WHERE `varcharvalue`=\'#varcharvalue\'";
var connection = new MySqlConnection(_connectionString);
try
{
connection.Open();
}
catch (Exception ex)
{
Log.Error(ex.ToString());
return null;
}
var cmd = new MySqlCommand(command, connection);
cmd.Parameters.AddWithValue("#varcharvalue",val );
MySqlDataReader reader;
try
{
reader = cmd.ExecuteReader();
}
catch (Exception ex)
{
connection.Close();
Log.Error(ex.ToString());
return null;
}
reader.Read();
if (reader.HasRows)
{
var cl = GetInstanse(reader);
reader.Close();
connection.Close();
return cl;
}
reader.Close();
connection.Close();
return null;
I am developing a Java web application using Hibernate, but there is a part of it where I want to use JDBC because I am creating look-up tables dynamically.
After a few minutes of using my web app I get this error:
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException:
Data source rejected establishment of
connection, message from server: "Too
many connections"
I know that using session.connection() is deprecated but I just want to get the underlying JDBC connection. I experimented using the session.doWork() but the error still occurred as it had before.
Here is what the code looks like:
Domain Layer:
/**
* Goes through the list of lookupTableAbstractions and persists each one
* #param lookupData
*/
public void updateLookupValues( List<LookupTableAbstraction> lookupData )
{
lookupTablesData.dropAllLookupTables(lookupData);
lookupTablesData.createLookupTables(lookupData);
for (LookupTableAbstraction lookupTable : lookupData)
lookupTablesData.persistLookupTableValues(lookupTable);
}
Data Layer:
public LookupTableAbstraction getLookupTable( String tableName )
{
LookupTableAbstraction lookupTable = new LookupTableAbstraction();
Session session = getSessionFactory().openSession();
String sqlQuery = "select value from " + tableName;
List<String> lookupTableValues = session.createSQLQuery(sqlQuery).list();
session.close();
lookupTable.setTableName(tableName);
for (String value : lookupTableValues)
lookupTable.addValue(value);
return lookupTable;
}
/**
* Persists the passed in lookup table.
* The lookup table that is used is determine by
* the tableName field of the passed in lookupTable
* #param lookupTable
*/
public void persistLookupTableValues( LookupTableAbstraction lookupTable )
{
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Connection connection = null;
try
{
connection = getJDBCConnectionFromHibernate(session);
Statement stmt = connection.createStatement();
String tableName = lookupTable.getTableName();
for (String value : lookupTable.getValues() )
{
String sql = " insert into " + tableName +
" (value) " +
" values " +
"('" + value + "')";
System.out.println(sql);
stmt.executeUpdate(sql);
}
stmt.close();
}
catch( Exception e )
{
System.out.println("Exception(persistLookupTableValues): " + e.getMessage());
e.printStackTrace();
}
finally
{
try {
tx.commit();
connection.close();
session.close();
} catch (SQLException e) {
System.out.println("Exception(persistLookupTableValues): " + e.getMessage());
e.printStackTrace();
}
}
}
/**
* Drop's all lookup tables.
* It drops each table based off the lookupTableAbstractions in the passed in list
* #param lookupData
*/
public void dropAllLookupTables( List<LookupTableAbstraction> lookupData )
{
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Connection connection = null;
try
{
connection = getJDBCConnectionFromHibernate(session);
Statement stmt = null;
for (LookupTableAbstraction lookupTableAbstraction : lookupData) {
stmt = connection.createStatement();
stmt.executeUpdate("drop table " + lookupTableAbstraction.getTableName());
}
stmt.close();
}
catch( Exception e )
{
System.out.println("Exception(dropAllLookupTables): " + e.getMessage());
e.printStackTrace();
}
finally
{
try {
tx.commit();
connection.close();
session.close();
} catch (SQLException e) {
System.out.println("Exception(dropAllLookupTables): " + e.getMessage());
e.printStackTrace();
}
}
}
/**
* Creates all lookup tables, one for each lookupTableAbstraction
* in the passed in list
* #param lookupData
*/
public void createLookupTables( List<LookupTableAbstraction> lookupData )
{
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Connection connection = null;
try
{
connection = getJDBCConnectionFromHibernate(session);
Statement stmt = null;
for (LookupTableAbstraction lookupTableAbstraction : lookupData) {
stmt = connection.createStatement();
stmt.executeUpdate("create table " + lookupTableAbstraction.getTableName() +
" ( ID int(11) auto_increment, " +
" value text, " +
" primary key (ID) )");
}
stmt.close();
}
catch( Exception e )
{
System.out.println("Exception(createLookupTables): " + e.getMessage());
e.printStackTrace();
}
finally
{
try {
tx.commit();
connection.close();
session.close();
} catch (SQLException e) {
System.out.println("Exception(createLookupTables): " + e.getMessage());
e.printStackTrace();
}
}
}
protected Connection getJDBCConnectionFromHibernate( Session session )
{
return session.connection();
}
Thanks for any suggestions
Same problem here. A lot of the examples on the internet forget to close out the session factory. If you don't close this out you will get the mysql "too many connections" error. Close it out with this line of code:
fact.close();
Assuming you named it fact like this:
SessionFactory fact = new Configuration().configure().buildSessionFactory();
I fixed the problem.
I was creating the session factory over and over.
So, I did this:
protected static SessionFactory sessionFactory = null;
static
{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
/**
* Returns a Hibernate session factory
* #return
*/
protected static SessionFactory getSessionFactory()
{
return sessionFactory;
}