Connection String to MySQL Temporary Table in Java - java

I am trying to create a temporary table in memory in order to store some data in it and use it within the application life time..
I am trying to do something as follows:
StringBuilder sb = new StringBuilder();
sb.append("CREATE TEMPORARY TABLE XmlItems ENGINE=MEMORY AS (");
// Continue with columns definitions
sb.append(")");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/");
Statement stat = conn.createStatement();
stat.executeUpdate(sb.toString());
But the following exception is being thrown:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
I'm guessing it has to do something with the connection string..
Any ideas?

You haven't provided schema name in the jdbc connection URL. Try after adding schema name at the end of URL.
jdbc:mysql://localhost:3306/myschema

The connection string has to contain a database schema to connect to.
DriverManager.getConnection("jdbc:mysql://localhost:3306/myTestDB");
Also, make sure that MySQL is actually running. "Communications link failure" sounds more like the connection to port 3306 is refused.

Check to make sure that the database in this case mysql is started/running, the connection String look fine despite the fact the you've not added the database name to be used instead of "jdbc:mysql://localhost:3306/" use "jdbc:mysql://localhost:3306/databae_name"

Related

How do I avoid an 'unknown database' error when using a custom database directory?

I'm working on a project and I have put my database folder in project folder. How can I make a database connection to any directory rather than just default MySQL dir in Java?
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
String UserName = "root";
String Password = "admin";
Connection con = null;
try {
con = DriverManager.getConnection(MySQLURL,UserName,Password);
if (con != null) {
System.out.println("Database connection is successful !!!!");
}
} catch (Exception e) {
e.printStackTrace();
}
When doing this, I get this error:
java.sql.SQLSyntaxErrorException: Unknown database 'c:\program files\snakegame'
Your connection URL is wrong
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
I am not sure why your MySQLURL contains C:\Program Files\SnakeGame
The connection URL for the mysql database is
jdbc:mysql://localhost:3306/[DatabaseName]
Where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running (we may also use the server's IP address here), 3306 is the port number, and [DatabaseName] is the name of the database created on the MySQL server.
Replace the [DatabaseName] name accordingly after creating the database in MySQL server
Combining localhost:3306/ with C:\\Program Files\\SnakeGame makes little sense for any database - either you're trying to connect to a file-based database (in which case the localhost... part makes no sense) or you're working with a server-based one (in which case the C:\... part makes no sense.
Also, this connection string would make little sense for a file-based database either because you didn't specify a specific file, just a path.
Incidentally, MySQL is server-based, not file-based. It's expecting a database name after the localhost:3306/ part, not a path (hence the error). The physical location of the actual database program is an installation/configuration issue - it has nothing to do with how you actually connect to the database server once it's already running.
Think about it this way: when you call an external database, web service, or web site, do you need to know which physical folder it's deployed to? Obviously not. The physical folders involved are completely irrelevant when calling MySQL or another database like this.
One of the comments pointed this out, but did you intend to use SQlite or some other file-based database here instead?

Establishing JDBC through SID

I am connecting to Oracle 11g DB trough my java program.
I am using Service Name and not SID.
addr = jdbc:oracle:thin:#hostIP:1521:ServiceName
Class.forName("oracle.jdbc.OracleDriver");
Connection con = DriverManager.getConnection(addr,un,pw);
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery(SELECT * from Table);
This works great. I am able to connect to DB and retrieve the data.
However, if I pass Service ID instead of Service Name, code doesn't work! I get exception.
I tried solution mentioned here - Java JDBC - How to connect to Oracle using Service Name instead of SID. But i still see the same exception.
addr should be in this way for service Name.
addr = jdbc:oracle:thin:#hostIP:1521/ServiceName
Using the Service Name
Syntax:
jdbc:oracle:thin:#//[host]:[tcpPort]/[service_name]
[host]: host name of the database server
[tcpPort]: database listener port
[service_name]: system identifier for the database
Example:
jdbc:oracle:thin:#//myhost:1525/myserviceDB
Please refer below article
https://docs.oracle.com/cd/E12518_01/central_office/pdf/141/html/co_ig/Output/appendix_url.htm

jdbc connection error with MySQL to netbeans. Error message Got an exception! com.mysql.jdbc.Driver

I encounter error when connecting my java project to database using MySQL.
I am now using Netbeans 6.8
seems that the database can not be accessed due to the driver error. so my connection code is like below
Connection con = null;
String url = "jdbc:mysql://localhost:3306/mila";
String db = "";
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
con = (Connection) DriverManager.getConnection(url + db, "root", "");
and the error message is stated below
Got an exception!
com.mysql.jdbc.Driver
and it points to the line where driver lied.
i already use this code in other project but no problem with it. i have also check the database name and such but no problem with that.
really appreciate for the help. thank you
I would wrap the operation in a try/catch block and log everything about the exception (e.g. e.printStackTrace(), etc.). Worthwhile enabling JDBC tracing just to see what the DriverManager says... like this: DriverManager.setLogStream(System.out); Oh, an try logging in from mysql's command line just to check server operation..

When using JDBC with Oracle DB how to find if the connection really timed out or if credentials were wrong?

I already have the connection string and DBA username. I accept DBA password from the user.
To check if the password provided by him is correct, I try to create a connection using
String connString = "jdbc:oracle:thin:#" + connDesc;
Properties props = new Properties();
props.put("user", user);
props.put("password", pwd);
props.put("internal_logon", "sysdba");
Class.forName("oracle.jdbc.OracleDriver").newInstance();
Connection conn = DriverManager.getConnection(connString, props);
Now when it throws SQLException I need to find if that exception is because of wrong password or network timeout. Is there any way to do that?
Also, is there any better way to validate password than what I'm currently doing?
You can use the SQLException.getErrorCode() method to read the Oracle-specific error code for the error.
For an invalid username/password combination, the error code is 1017.
It's not clear to me exactly what error you mean by 'network timeout'. If the message is The Network Adapter could not establish the connection, then the error code you want appears to be 17002. (I got this error attempting to connect to my local Oracle XE instance using JDBC but with the TNS listener shut down.)
There isn't a better way of validating a username/password than attempting to create a connection to the database using that username and password.

JDBC Connection Issue

I have create a getDBConnection method in my Java application. This returns a connection object, and hence I haven't closed this connection in this method itself.
Now, I am invoking this method from various methods in my application at regular intervals, and closing them inside a try - finally block. I thought this should free up the connection after use. However, I am seeing a large number of connections opened (about 50) in the MySQL Administrator's Server Connections tab.
//Defining a method to retrieve a database connection
// PropDemo is a properties class that retrieves Database related values from a file
public Connection getDBConnection() {
//Instantiating the Properties object
PropDemo prop = new PropDemo();
Connection con = null;
// Retrieving values from the parameters.properties file
String JdbcDriver = prop.getMessage("JdbcDriver");
String JdbcUrlPrefix = prop.getMessage("JdbcUrlPrefix");
String DBIP = prop.getMessage("DBIP");
String DBName = prop.getMessage("DBName");
String DBUser = prop.getMessage("DBUser");
String DBPassword = prop.getMessage("DBPassword");
try {
// Loading and instantiating the JDBC MySQL connector driver class
Class.forName(JdbcDriver).newInstance();
con = DriverManager.getConnection(JdbcUrlPrefix + DBIP + "/" + DBName, DBUser, DBPassword);
if (con.isClosed())
Logger.log("Connection cannot be established", "vm");
} catch (Exception e) {
Logger.log("Exception: " + e, "vm");
Logger.log(Logger.stack2string(e), "vm");
}
return con;
}
I am also closing the associated ResultSet and Statement Objects. What could be missing here?
I am planning to replace all the Statements with PreparedStatements for efficiency and security reasons. Will that help significantly? What else can be done?
EDIT:
This is just a core java application that is repeatedly quering for changes in some fields in a MySQL database through MySQL-JDBC connector. I am not using any framework like Spring or Hibernate.
Your code looks sane.
That's how you're creating a new connection.
Probably the error is where you close it.
You should close it in a finally block.
Some additional questions.
1) Are you sure those 50 conections come from this program ? Maybe there are some others comming from your same office. To confirm this you would need to stop the program, and look again in your connection monitor.
2) Does your application uses many connection simultaneously? Probably its a peak when you're using 50 at the same time.
If you can post the code where you close the connection. Chances are the problem is there.
Additionally I would suggest you to use a connection pool. You can build one your self or you can see the results from this page:
How many JDBC connections in Java?
Are you closing the connection object when you application closes as well?
Are you using your JDBC connection within a J2EE application server or with Hibernate?
Both of these tend to start out with a fairly high connection pool to begin with, so you would see a large number.
Check out the details on connection pooling.
You could take a Singleton approach to the problem and only create a new Connection object if the current one is null:
If (connectionObject != null){
return connectionObject;
}else {
//create new connection object
}
This will make sure that you only have one non-null connection at any time.

Categories