I've strange problem.
I'm using GWT on AppEngine and I want to create RPC which connect to MySql. All this day I'm sitting on it.. This is my implementation of RPC methods:
java.sql.Connection con = null;
public DataBaseServiceImpl() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.print("bladd..");
e.printStackTrace();
}
String url ="jdbc:mysql://localhost:8806/base";
try {
con = DriverManager.getConnection( url,"root", "");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public ArrayList<String[]> getTables(int idUser) throws SQLException {
Statement st = con.createStatement();
ResultSet retrive = st.executeQuery("query");
ArrayList<String[]> result = new ArrayList<String[]>();
while(retrive.next())
{
String[] s = new String[2];
int theInt= retrive.getInt("ID__TABLE");
String str = retrive.getString("LABEL");
s[0]=Integer.toString(theInt);
s[1]=str;
result.add(s);
}
return result;
}
And I have this error:
java.sql.SQLException: Unable to initialize driver properties due to
java.lang.IllegalAccessException: Class
com.google.appengine.tools.development.agent.runtime.Runtime can not
access a member of class com.mysql.jdbc.ConnectionPropertiesImpl with
modifiers "private"
I don't have any idea what it is.
Could someone help me?
Regards.
Well the bottom line is you have really messy code. There are many violations to good coding practice.
From the code you included this line never gets executed:
con = DriverManager.getConnection( url,"root", "");
So there is no connection to your db. Does your exception indicate that this line
Statement st = con.createStatement();
is the problem?
I had the same problem running on jre1.7.0_25.
I resolved it by upgrading to jre1.7.0_45.
Related
I'm trying to connect my Java code to a db I've created in Google Cloud SQL, but I'm getting ClassNotFound and SQLException errors: -
java.lang.ClassNotFoundException: com.google.cloud.sql.mysql.SocketFactory
java.sql.SQLException: No suitable driver found for jdbc:mysql
I'm also getting a NullPointerException in code, in the getAllFilms() method at the line below, which I'm assuming is because the code isn't making a db connection: -
ResultSet rs1 = stmt.executeQuery(selectSQL);
Things I've done so far: -
Tested the Google Cloud SQL db credentials, through a client connection
Reviewed related posts, particularly [this one][1]
Been through the Google documentation
Added MySQL and Socket Factory Connector(j8) JARs to my project dependencies
Unfortunately I'm still unable to resolve. Hopefully someone can help. I've attached my Java code below. Thanks in advance...
Film oneFilm = null;
Connection googleSqlConnection = null;
Statement stmt = null;
String url = "jdbc:mysql:///<dbname>?<cloudSqlInstance>&socketFactory=com.google.cloud.sql.
mysql.SocketFactory&user=<user>&password=<pword>";
public FilmDAO() {
}
private void openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.google.cloud.sql.mysql.SocketFactory");
} catch (Exception e) {
System.out.println(e);
}
try {
googleSqlConnection = DriverManager.getConnection(url);
stmt = googleSqlConnection.createStatement();
} catch (SQLException se) {
System.out.println(se);
}
}
private void closeConnection() {
try {
googleSqlConnection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<Film> getAllFilms() {
ArrayList<Film> allFilms = new ArrayList<>();
openConnection();
try {
String selectSQL = "select * from films limit 50";
ResultSet rs1 = stmt.executeQuery(selectSQL);
while (rs1.next()) {
oneFilm = getNextFilm(rs1);
allFilms.add(oneFilm);
}
stmt.close();
closeConnection();
} catch (SQLException se) {
System.out.println(se);
}
return allFilms;
}
[1]: https://stackoverflow.com/questions/53693679/connecting-to-google-cloud-sql-with-java
Have you added the Cloud SQL JDBC SocketFactory and mysql-connector-java to your pom.xml?
We have created jar file for a java method and imported it in SOAPUI. We are able to call method, however not able to retrieve query result returned in ResultSet by java method in groovy script def dataRow = GetData.GetRecords(preQuery). I am new to groovy script.
Below is method we have written in java and created jar for it.
package getRecords;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class GetData {
protected static Connection con = null;
protected static Statement stmt = null;
protected static ResultSet result = null;
//Opening DB connection
public static void OpenDBConnection(String dbUrl, String driver, String username, String password){
//Making connection to DB
try {
Class.forName(driver);
con = DriverManager.getConnection(dbUrl, username, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Closing DB connection
public static void CloseDBConnection(){
try {
//Closing DB connection
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Executing query and fetching data from DB
public static ResultSet GetRecords(String query){
//Executing query and saving result into result set
try {
stmt = con.createStatement();
result = stmt.executeQuery(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void main(String args[]){
System.out.println("DBConnection..");
GetData gd = new GetData();
GetData.OpenDBConnection("jdbc:oracle:thin:#test:1530/test", "oracle.jdbc.driver.OracleDriver", "******", "******");
System.out.println("DB");
}
}
I suspect your result set is being closed when you return from GetRecords (tip: use camel case for Java method names, starting with a lower-case character) and you may also be jumping JVMs. See also Is it Ok to Pass ResultSet?.
You probably don't need to use your result set as a result set back in soapUI, you just want the data, so a better option would be to populate a bean and return a List of those instead:
public static List<MyBean> GetRecords(String query){
List<MyBean> myBeans = new ArrayList<>();
//Executing query and saving result into result set
try {
stmt = con.createStatement();
result = stmt.executeQuery(query);
while (result.next()) {
MyBean myBean = new MyBean();
// Populate the bean...
myBeans.add(myBean);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return myBeans;
}
You might also want to investigate the try-with-resources feature that came out with Java 7: it'll handle the closing of your connections automatically.
In SoapUi you can directly do the JDBC call using Groovy scripting.
If you wanted to do some Database operation in soapUI you can write the code in groovy using the corresponding database driver ( DB2, Oracle, Mysql), Until or unless any specific reason to use jar file as you have mentioned.
Making the database connection you need to download and place the jar files inside ( SoapUi install folder/bin/ext
eg.. for Oracle (ojdbc6.jar, orai18n.jar)
EDIT:
I was testing out this code that I found in another post to look for the database name:
public static String getDBname(Connection conn) {
String result = null;
int i = 0;
try {
ResultSet rs = conn.getMetaData().getCatalogs();
while (rs.next()) {
System.out.println(rs.getString(i));
i ++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
However it just returns me this error:
net.ucanaccess.jdbc.FeatureNotSupportedException: Feature not supported.
at net.ucanaccess.jdbc.UcanaccessDatabaseMetadata.getCatalogs(UcanaccessDatabaseMetadata.java:310)
Is there another way to do this?
For UCanAccess, the "database name" is just the name of the .accdb or .mdb file. That can be retrieved by extracting it from the connection URL as returned by
conn.getMetaData().getURL()
e.g.,
jdbc:ucanaccess://C:/Users/Public/UCanAccessTest.accdb;memory=false
I am pretty new to Java so I'm working on a project to develop my knowledge with databases and Java.
I have figured out how to add queries into the database but now I'm getting errors when trying to print them out.
Assume I already have everything that's necessary imported in such as the scanner and sql statements
Here is my connection class which is named MainClass:
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testTable";
String username = "placeholder";
String password = "placeholder";
Class.forName(driver);
Connection conn = Driver Manager.getConnection(url, username, password);
return conn;
}
Now in a different class if the user types !lookup and a word I want the definition of that word to be retrieved from the table whose name is dictionary and columns are word, definition:
String userSearch = user_input.next();
String[] userSearchSplit = userSearch.split(" ", 3);
if (userSearchSplit[0].equals("!lookup")) {
try {
conn = MainClass.getConnection();
String query = "select definition from dictionary where word=" + userSearchSplit[1];
ResultSet result = pstmt.executeQuery(query);
while (result.next()) {
String definition = result.getString("definition");
System.out.println(definition);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
At the end of all this when I try to look up a word I put in the table before running I get:
java.lang.NullPointerException
Check if your user_input is null?
I am assuming your code:
ResultSet result = pstmt.executeQuery(query);
as
Statement pstmt = conn.createStatement();
ResultSet result = pstmt.executeQuery(query);
Or it could be that you have not initialized the pstmt properly
I have a Java program in which I am doing some JDBC for select queries. Will it be advisable to call testDataBase() each time which inturns calls DBConnection() each time or I should reuse one connection for all the queries. Thanks in advance.
private void testDataBase(String query){
Connection con = DBConnection();
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
rs = st.executeQuery(query);
boolean flag = true;
while (rs.next()) {
String resultString = "";
for(int i = 1; i <=rs.getMetaData().getColumnCount();i++){
resultString=resultString+" "+ rs.getString(i);
}
System.out.println(resultString);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private Connection DBConnection() {
final String method_name = "DBConnection";
Connection conn = null;
try{
Class.forName(driver).newInstance();
conn = java.sql.DriverManager.getConnection(url,userName,password);
}catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return conn;
}
Opening a DB connection is an expensive operation in terms of perfofmance. You should use a ConnectionPool for sharing connections among different requests.
Connections are not thread safe, so sharing them across requests is not a good idea.
A better idea is to pool connections and keep their scope as narrow as possible: check the connection out of the pool, use it, close it in transaction scope.
Database connections are long-running and should be re-used, unless you have a very low query rate.
Getting a database connection is quite an expensive operation, so it is advisable to re-use a connection if possible. Consider also using connection pooling, which will maintain a number of connections for you, so you can just grab one from the pool when needed. The method shown above might not need to change, it depends on the DBConnection() method you call.
I completely agree with #Amir Kost, in terms of performances, opening a DB connection in one of the slowest operation that you can do, and if you have restrictive real time constraints it could be a big issue.
I do not know if you are using a framework or not, but a good practice is to publish a bean which wrap a pool of connection and every time that you need to interact directly with the db, you get the current open connection (which usually corresponds to a so called "session").
I suggest to you, (even if you are not using any framework) to reproduce this technicality.
If you want only one instance of Connection, you can make use of the Singleton pattern, you can consider :
public class Connector {
private static final String URL = "jdbc:mysql://localhost/";
private static final String LOGIN = "root";
private static final String PASSWORD = "azerty";
private static final String DBNAME = "videotheque";
private static Connector connector;
private static Connection connection;
private Connector() {
}
public synchronized static Connector getInstance() {
if (connector == null) {
connector = new Connector();
}
return connector;
}
public static Connection getConnection() {
if (connection == null) {
Connection c = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
c = DriverManager.getConnection(URL + DBNAME, LOGIN, PASSWORD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return c;
}
return connection;
}
}
And then, you can call : Connector.getInstance().getConnection()