I got to use MariaDB for my University Project.
it's my first time doing it, so I dont't know well how to use and code JDBC Driver and mariaDB.
Now I'm implementing the code in many places while looking at examples.
As I see, All the examples seems to creating Statement and making connection by using "DriverManager.getConnection"
Now I have a question.
I'm going to create a DBmanager Class that can connect, create tables, execute queries, and execute the code that updates data on tables in a single line.
I thought all the examples would run alone in one method and came from different places, so I could only try a new connection and create a code that would not close. But I have a gut feeling that this will be a problem.
Is there any way I can leave a connection connected at a single connection to send a command, and disconnect it to DB.disconnect()? And I'd appreciate it if you could tell me whether what I'm thinking is right or wrong.
The code below is the code I've written so far.
I am sorry if you find my English difficult to read or understand. I am Using translator, So, my English could not be display as I intended.
import java.sql.*;
import java.util.Properties;
public class DBManager {
/*********INNITIAL DEFINES********/
final static private String HOST="sumewhere.azure.com";//Azure DB URL
final static private String USER="id#somewhere";//root ID
final static private String PW="*****";//Server Password
final static private String DRIVER="org.mariadb.jdbc.Driver";//DB Driver info
private String database="user";
/***************API***************/
void setDB(String databaseinfo){
database=databaseinfo;
}
private void checkDriver() throws Exception
{
try
{
Class.forName("org.mariadb.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
}
public void checkOnline(String databaseinfo) throws Exception
{
setDB(databaseinfo);
this.checkDriver();
Connection connection = null;
try
{
String url = String.format("jdbc:mariadb://%s/%s", HOST, database);
// Set connection properties.
Properties properties = new Properties();
properties.setProperty("user", USER);
properties.setProperty("password", PW);
properties.setProperty("useSSL", "true");
properties.setProperty("verifyServerCertificate", "true");
properties.setProperty("requireSSL", "false");
// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
void makeCcnnection() throws ClassNotFoundException
{
// Check DB driver Exists
try
{
Class.forName("org.mariadb.jdbc");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
Connection connection = null;
}
public void updateTable(){}
public static void main(String[] args) throws Exception {
DBManager DB = new DBManager();
DB.checkOnline("DB");
}
}
For a studying project it's okay to give a connection from your DB Manager to client code and close it there automatically using try-with-resources construction.
Maybe you will find it possible to check Connection Pool tools and apply it further in your project or use as example (like HikariCP, here is a good introduction).
Read about Java try with resources. I think that this link could be usefull for your problem.
JDBC with try with resources
Related
Heading ##I have problem with my java application with database in mySQL and swing GUI.
When I've used localhost everything worked properly. But now I would like to share project with my friend and we decided to use server hosting.
And here is a problem:
Now application works very slow, after pressing a button I have to wait a few seconds for the program to respond. Also the connection is lost from time to time. I have no idea where can I find reason for the problem... Do somebody now what is the reason of this problem?
private static Connection connection = null;
Boolean error = false;
private static String jdbcURL = "jdbc:mysql://host_name:3306/db_name";
private static String user = "user";
private static String password = "password";
MakeConnection(Connection connection) throws SQLException{
this.connection = connection;
try {
getConnection();
System.out.print("Connected to the data base in MakeConnection");
}
catch(Exception e) {
error = true;
System.out.print("Error in connection in MakeConnection consturctor" + e.getMessage());
}
finally{
if(connection!=null) connection.close();
if(error) System.out.print("Problem with connection");
else System.out.print("Program finished");
}
}
public Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL,user,password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
Also sometimes application shows this error:
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I don't see any problem in your code. The problem is probably with your server hosting. You should check the country of the host provider and measure the time required to send a request to the server. Also you should use logger instead of System.out.println so you can examine required time for actions like db access, application logic and find a bottleneck.
I have a problem when running my code in NetBeans in order to see if mySQL is connected. This is the code:
public static void main(String[] args) {
Connection connect = null;
try{
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}
}
}
when I run it prints out "RIP". When I debugged it line by line, it went from the "connect = DriverManager.getConnection..." to "System.out.println("RIP"), and when I look at the "Exception e" it says "e = (java.sql.SQLNonTransientConnectionException) java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the connection string near '=TRUE'."
Now, why is that?????
I think you need to add
Class.forName("com.mysql.jdbc.Driver"); .
Also, make sure everything in Connection conn = DriverManager.getConnection (String url, String user, String password); are set correctly.
From the url format in your code, it's like you are trying to get direct connect to specific table tUsers in your database. And I dont think that would work. Correct me if I'm wrong whether it's literally your database name or not.
Because the basic url format i know, should be like jdbc:mysql://localhost:3306/yourDBname .
If you already set the url correctly as is written in your post, then the code is
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}}}
Hope that could do the work.
I have a class that tries to connect to a Heroku database:
public class ConnectionFactory {
public Connection getConnection() {
System.out.println("Conectando ao banco");
try {
return DriverManager.getConnection("connectionstring", "username", "password");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
What it returns is:
java.lang.RuntimeException: java.sql.SQLException: No suitable driver
found for
jdbc:postgres://osnvehqhufnxzr:TS3Qt37c_HHbGRNKw3yk7g88fp#ec2-54-225-93-34.compute-1.amazonaws.com:5432/d39mfq0odt56bv
I already tried postgresql-9.3-1103.jdbc3.jar and postgresql-9.4.1209.jre6.jar
in the Build Path of the project. What I am doing wrong?
Use postgresql in your JDBC URL and not postgres.
Also, you need to change your DB password (because you posted it publicly) by running this command:
$ heroku pg:credentials DATABASE --reset
You need to load the driver class first by the class loader:
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(...);
Also see: What is the purpose of 'Class.forName("MY_JDBC_DRIVER")'?
The solution was simple, System.getenv("JDBC_DATABASE_URL") returns it in server and it does the correct configuration of login and password.
public Connection getConnection() throws URISyntaxException, SQLException
{
String urlDB = System.getenv("JDBC_DATABASE_URL");
return DriverManager.getConnection(urlDB);
}
I am using Eclipse and tomcat 7. I have little experience with either product and for that matter Java itself. I was trying to connect to a derby database from a Servlet. Initially, all I had in my doGet() is the following:
conn = DriverManager.getConnection(connectionURL);
I have connectionURL defined as
static private String connectionURL = "jdbc:derby://localhost:1527/seconddb";
Then I added the following to the Build Path and Deployment Assembly.
C:\DERBY\db-derby-10.10.1.1-bin\lib\derbyclient.jar
That is all I did. I sort of assumed that Tomcat will find the driver class and load it. I got the following error
java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/seconddb
Then I went on to add the following code in doGet() to load the driver class:
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Now it worked. I thought that after Java 1.4 there was no need to explicitly load JDBC driver class. So what am I doing wrong here? I have given the entire code below.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
try {
conn = DriverManager.getConnection(connectionURL);
//DriverManager.getConnection("jdbc:derby://localhost:1527/testdb;create=true");
}
catch (SQLException e) {
e.printStackTrace();
}
PrintWriter p = response.getWriter ();
p.println("Connected to database");
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
I am using java 1.7
I cannot really explain why, but here is how I do :
if the driver is located in the war, I must call Class.forName("...Driver"); in in initialization method somewhere in the web application.
if the driver is located in Tomcat libraries, it is automacally loaded when I need it.
I know it's more a rule of thumb than a clear explaination, but my knowledge in class loading does not allow me to a better answer ...
Your Derby driver doesn't support the JDBC 4 auto-loading, so you have to do it manually. Try to find a more up to date version.
I could be wrong here but in your second code sample connectionURL
static private String connectionURL = "jdbc:derby://localhost:1527/seconddb";
doesn't include "create=true"; to complete the statement. In your full code sample it's included, but commented out.
import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:3306:procomport";
//Class.forName ("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
//Connection connection = DriverManager.getConnection(url , userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
This is my code I have multiple different databases but it wont connect to any of them what's the problem with this? I keep getting the error it cannot connect to the database. Although I can connect to it using other management tools is it a driver issue? How would I be able to tell if I had the drivers necessary?
The code you've provided to connect to the database won't connect to either MySQL nor Oracle as it stands because it's a mish-mash of attempts to connect to both.
For Oracle, the code should look something like:
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:1521:procomport";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
(assuming you have a user called root on Oracle, and the Oracle SID is procomport). Note in particular the change of port number: MySQL typically uses 3306, Oracle uses 1521.
For MySQL the connection code should look like:
String userName = "root";
String password = "password123!";
String url = "jdbc:mysql://localhost:3306/procomport";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
(assuming your MySQL database is called procomport). Note the different style of connection URL and the driver class name.
The Oracle driver is typically in a JAR file named ojdbc6.jar, and the MySQL in a JAR named something like mysql-connector-java-5.1.18-bin.jar.
Finally, when you write something like
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
you really aren't helping yourself. The exception e will almost certainly contain the reason why your database connection code isn't working, but by deliberately ignoring it you're making it much harder for yourself to figure out what has gone wrong.
To be honest with you, I'd be tempted to declare the main method throws Exception (by adding this to the end of the public static void main... line), and then you can delete your unhelpful catch block. If an exception is thrown and not handled within main, the JVM will print the stack trace for you before it exits.
After your:
System.err.println();
Place a:
e.printStacktrace();
Then you will see real error message. Probably the driver classes are not in the classpath.
Hope this will help you
Uncomment the line Class.forName("oracle.jdbc.driver.OracleDriver");
Make sure you have the Oracle dirver "oracle.jdbc.driver.OracleDriver" in the classpath