What is the MySQL JDBC driver connection string? - mysql

I am new to JDBC and I am trying to make a connection to a MySQL database.
I am using Connector/J driver, but I cant find the JDBC connection string for my Class.forName() method.

Assuming your driver is in path,
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, "username", "password");

Here's the documentation:
https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
A basic connection string looks like:
jdbc:mysql://localhost:3306/dbname
The class.forName string is "com.mysql.jdbc.Driver", which you can find (edit: now on the same page).

"jdbc:mysql://localhost"
From the oracle docs..
jdbc:mysql://[host][,failoverhost...]
[:port]/[database]
[?propertyName1][=propertyValue1]
[&propertyName2][=propertyValue2]
host:port is the host name and port number of the computer hosting your database. If not specified, the default values of host and port are 127.0.0.1 and 3306, respectively.
database is the name of the database to connect to. If not specified, a connection is made with no default database.
failover is the name of a standby database (MySQL Connector/J supports failover).
propertyName=propertyValue represents an optional, ampersand-separated list of properties. These attributes enable you to instruct MySQL Connector/J to perform various tasks.

It is very simple :
Go to MySQL workbench and lookup for Database > Manage Connections
you will see a list of connections. Click on the connection you wish to connect to.
You will see a tabs around connection, remote management, system profile. Click on connection tab.
your url is jdbc:mysql://<hostname>:<port>/<dbname>?prop1 etc.
where <hostname> and <port> are given in the connection tab.It will mostly be localhost : 3306. <dbname> will be found under System Profile tab in Windows Service Name. Default will mostly be MySQL5<x> where x is the version number eg. 56 for MySQL5.6 and 55 for MySQL5.5 etc.You can specify ur own Windows Service name to connect too.
Construct the url accordingly and set the url to connect.

For Mysql, the jdbc Driver connection string is com.mysql.jdbc.Driver. Use the following code to get connected:-
class DBConnection {
private static Connection con = null;
private static String USERNAME = "your_mysql_username";
private static String PASSWORD = "your_mysql_password";
private static String DRIVER = "com.mysql.jdbc.Driver";
private static String URL = "jdbc:mysql://localhost:3306/database_name";
public static Connection getDatabaseConnection(){
Class.forName(DRIVER);
return con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
}
}

As the answer seems already been answered, there is not much to add but I would like to add one thing to the existing answers.
This was the way of loading class for JDBC driver for mysql
com.mysql.jdbc.Driver
But this is deprecated now. The new driver class is now
com.mysql.cj.jdbc.Driver
Also the driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

update for mySQL 8 :
String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";

Here is a little code from my side :)
needed driver:
com.mysql.jdbc.Driver
download: here (Platform Independent)
connection string in one line:
jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false
example code:
public static void testDB(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false");
if (connection != null) {
Statement statement = connection.createStatement();
if (statement != null) {
ResultSet resultSet = statement.executeQuery("select * from test");
if (resultSet != null) {
ResultSetMetaData meta = resultSet.getMetaData();
int length = meta.getColumnCount();
while(resultSet.next())
{
for(int i = 1; i <= length; i++){
System.out.println(meta.getColumnName(i) + ": " + resultSet.getString(meta.getColumnName(i)));
}
}
resultSet.close();
}
statement.close();
}
connection.close();
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}

update for mySQL 8 :
String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";
Check whether your Jdbc configurations and URL correct or wrong using the following code snippet.
import java.sql.Connection;
import java.sql.DriverManager;
public class TestJdbc {
public static void main(String[] args) {
//db name:testdb_version001
//useSSL=false (get rid of MySQL SSL warnings)
String jdbcUrl = "jdbc:mysql://localhost:3306/testdb_version001?useSSL=false";
String username="testdb";
String password ="testdb";
try{
System.out.println("Connecting to database :" +jdbcUrl);
Connection myConn =
DriverManager.getConnection(jdbcUrl,username,password);
System.out.println("Connection Successful...!");
}catch (Exception e){
e.printStackTrace();
//e.printStackTrace();
}
}
}

The method Class.forName() is used to register the JDBC driver. A connection string is used to retrieve the connection to the database.
The way to retrieve the connection to the database is shown below. Ideally since you do not want to create multiple connections to the database, limit the connections to one and re-use the same connection. Therefore use the singleton pattern here when handling connections to the database.
Shown Below shows a connection string with the retrieval of the connection:
public class Database {
private String URL = "jdbc:mysql://localhost:3306/your_db_name"; //database url
private String username = ""; //database username
private String password = ""; //database password
private static Database theDatabase = new Database();
private Connection theConnection;
private Database(){
try{
Class.forName("com.mysql.jdbc.Driver"); //setting classname of JDBC Driver
this.theConnection = DriverManager.getConnection(URL, username, password);
} catch(Exception ex){
System.out.println("Error Connecting to Database: "+ex);
}
}
public static Database getDatabaseInstance(){
return theDatabase;
}
public Connection getTheConnectionObject(){
return theConnection;
}
}

String url = "jdbc:mysql://localhost:3306/dbname";
String user = "user";
String pass = "pass";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, user, pass);
3306 is the default port for mysql.
If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver").newInstance (); statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.
The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:
jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] ยป
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

protocol//[hosts][/database][?properties]
If you don't have any properties ignore it then it will be like
jdbc:mysql://127.0.0.1:3306/test
jdbc:mysql is the protocol
127.0.0.1: is the host and 3306 is the port number
test is the database

it's depends on what service you're using.
if you use MySQL Workbench it wold be some thing like this :
jdbc:mysql://"host":"port number"/
String url = "jdbc:mysql://localhost:3306/";
And of course it will be different if you using SSL/SSH.
For more information follow the official link of Jetbriens (intelliJ idea) :
Connecting to a database #
https://www.jetbrains.com/help/idea/connecting-to-a-database.html
Configuring database connections #
https://www.jetbrains.com/help/idea/configuring-database-connections.html

Check if the Driver Connector jar matches the SQL version.
I was also getting the same error as I was using the
mySQl-connector-java-5.1.30.jar
with MySql 8

Related

Getting error on calling APIs of APIMAN [duplicate]

How do you connect to a MySQL database in Java?
When I try, I get
java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
Or
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Or
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
Here's a step by step explanation how to install MySQL and JDBC and how to use it:
Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306.
Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).
If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.
If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application.
java -cp .;/path/to/mysql-connector.jar com.example.YourClass
The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used.
Create a database in MySQL. Let's create a database javabase. You of course want World Domination, so let's use UTF-8 as well.
CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Create a user for Java and grant it access. Simply because using root is a bad practice.
CREATE USER 'java'#'localhost' IDENTIFIED BY 'password';
GRANT ALL ON javabase.* TO 'java'#'localhost' IDENTIFIED BY 'password';
Yes, java is the username and password is the password here.
Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:
jdbc:mysql://hostname:port/databasename
hostname: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost. It can also be an IP address like 127.0.0.1. If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config.
port: The TCP/IP port where MySQL server listens on. This is by default 3306.
databasename: The name of the database you'd like to connect to. That's javabase.
So the final URL should look like:
jdbc:mysql://localhost:3306/javabase
Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection.
String url = "jdbc:mysql://localhost:3306/javabase";
String username = "java";
String password = "password";
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
If you get a SQLException: No suitable driver, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
Note that the newInstance() call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver. Explanation here. If this line throws ClassNotFoundException, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.
Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException: Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
Note that closing the Connection is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection in a try-with-resources statement. Or if you're not on Java 7 yet, explicitly close it in finally of a try-finally block. Closing in finally is just to ensure that it get closed as well in case of an exception. This also applies to Statement, PreparedStatement and ResultSet.
That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.
Using a Singleton Pattern for the DB connection is a bad approach. See among other questions: Is it safe to use a static java.sql.Connection instance in a multithreaded system?. This is a #1 starters mistake.
DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
or instantiating and configuring one from your database driver directly:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");
and then obtain connections from it, same as above:
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();
Initialize database constants
Create constant properties database username, password, URL and drivers, polling limit etc.
// init database constants
// com.mysql.jdbc.Driver
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250"; // set your own limit
Initialize Connection and Properties
Once the connection is established, it is better to store for reuse purpose.
// init connection object
private Connection connection;
// init properties object
private Properties properties;
Create Properties
The properties object hold the connection information, check if it is already set.
// create properties
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
Connect the Database
Now connect to database using the constants and properties initialized.
// connect database
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
// Java 7+
e.printStackTrace();
}
}
return connection;
}
Disconnect the database
Once you are done with database operations, just close the connection.
// disconnect database
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Everything together
Use this class MysqlConnect directly after changing database_name, username and password etc.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class MysqlConnect {
// init database constants
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250";
// init connection object
private Connection connection;
// init properties object
private Properties properties;
// create properties
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
// connect database
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return connection;
}
// disconnect database
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
How to Use?
Initialize the database class.
// !_ note _! this is just init
// it will not create a connection
MysqlConnect mysqlConnect = new MysqlConnect();
Somewhere else in your code ...
String sql = "SELECT * FROM `stackoverflow`";
try {
PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
... go on ...
... go on ...
... DONE ....
} catch (SQLException e) {
e.printStackTrace();
} finally {
mysqlConnect.disconnect();
}
This is all :) If anything to improve edit it! Hope this is helpful.
String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
String user = "username";
String password = "password";
// Load the Connector/J driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Establish connection to MySQL
Connection conn = DriverManager.getConnection(url, user, password);
Here's the very minimum you need to get data out of a MySQL database:
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/foo", "root", "password");
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM `FOO.BAR`");
stmt.close();
conn.close();
Add exception handling, configuration etc. to taste.
you need to have mysql connector jar in your classpath.
in Java JDBC API makes everything with databases. using JDBC we can write Java applications to
1. Send queries or update SQL to DB(any relational Database)
2. Retrieve and process the results from DB
with below three steps we can able to retrieve data from any Database
Connection con = DriverManager.getConnection(
"jdbc:myDriver:DatabaseName",
dBuserName,
dBuserPassword);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.
Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA
MySQL JDBC Connection with useSSL.
private String db_server = BaseMethods.getSystemData("db_server");
private String db_user = BaseMethods.getSystemData("db_user");
private String db_password = BaseMethods.getSystemData("db_password");
private String connectToDb() throws Exception {
String jdbcDriver = "com.mysql.jdbc.Driver";
String dbUrl = "jdbc:mysql://" + db_server +
"?verifyServerCertificate=false" +
"&useSSL=true" +
"&requireSSL=true";
System.setProperty(jdbcDriver, "");
Class.forName(jdbcDriver).newInstance();
Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
Statement statement = conn.createStatement();
String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + "\"" + letterID + "\"";
ResultSet resultSet = statement.executeQuery(query);
resultSet.next();
return resultSet.getString(1);
}
Short and Sweet code.
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
//Database Name - testDB, Username - "root", Password - ""
System.out.println("Connected...");
} catch(Exception e) {
e.printStackTrace();
}
For SQL server 2012
try {
String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123";
//KHILAN is Host and 1433 is port number
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver Loaded");
conn = DriverManager.getConnection(url);
System.out.println("Connected...");
} catch(Exception e) {
e.printStackTrace();
}
Connection I was using some time ago, it was looking like the easiest way, but also there were recommendation to make there if statement- exactly
Connection con = DriverManager.getConnection(
"jdbc:myDriver:DatabaseName",
dBuserName,
dBuserPassword);
if (con != null){
//..handle your code there
}
Or something like in that way :)
Probably there's some case, while getConnection can return null :)
HOW
To set up the Driver to run a quick sample
1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J
2. Remember to set the classpath to include the path of the connector jar file.
If we don't set it correctly, below errors can occur:
No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development
java.lang.ClassNotFoundException: com.mysql.jdbc:Driver
To set up the CLASSPATH
Method 1: set the CLASSPATH variable.
export CLASSPATH=".:mysql-connector-java-VERSION.jar"
java MyClassFile
In the above command, I have set the CLASSPATH to the current folder and mysql-connector-java-VERSION.jar file. So when the java MyClassFile command executed, java application launcher will try to load all the Java class in CLASSPATH.
And it found the Drive class => BOOM errors was gone.
Method 2:
java -cp .:mysql-connector-java-VERSION.jar MyClassFile
Note: Class.forName("com.mysql.jdbc.Driver"); This is deprecated at this moment 2019 Apr.
Hope this can help someone!
MySql JDBC Connection:
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");
Statement stmt=con.createStatement();
stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("Select * from Table");
Short Code
public class DB {
public static Connection c;
public static Connection getConnection() throws Exception {
if (c == null) {
Class.forName("com.mysql.jdbc.Driver");
c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");
}
return c;
}
// Send data TO Database
public static void setData(String sql) throws Exception {
DB.getConnection().createStatement().executeUpdate(sql);
}
// Get Data From Database
public static ResultSet getData(String sql) throws Exception {
ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
return rs;
}
}
Download JDBC Driver
Download link (Select platform independent): https://dev.mysql.com/downloads/connector/j/
Move JDBC Driver to C Drive
Unzip the files and move to C:\ drive. Your driver path should be like C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19
Run Your Java
java -cp "C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19.jar" testMySQL.java
testMySQL.java
import java.sql.*;
import java.io.*;
public class testMySQL {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("show databases;");
System.out.println("Connected");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Inserting into mysql database using jsp throwing exception

I am trying to store information from a registration form page to the corresponding database but the code is throwing the exception as stated 'unable to connect to database' I am a beginner and having a hard time trying to figure out what's going wrong in this. Can somebody please help?
<%#page import="java.sql.*"%>
<html>
<head>
<meta charset="utf-8">
<title>Sign Up</title>
<link rel="stylesheet" type="text/css" href="reg.css">
</head>
<body>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String password = request.getParameter("password");
String date = request.getParameter("date");
String sex = request.getParameter("sex");
Connection con = null;
PreparedStatement ps = null;
String connectionURL = "jdbc:mysql://localhost:3306/table";
String driverName = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
Class.forName(driverName).newInstance();
try {
con = DriverManager.getConnection(connectionURL, user, pass);
String queryString = "INSERT INTO detail(name,password,email,date,sex) VALUES (?,?,?,?,?)";
ps = con.prepareStatement(queryString);
ps.setString(1, name);
ps.setString(2, password);
ps.setString(3, email);
ps.setString(4, date);
ps.setString(5, sex);
int updateQuery = ps.executeUpdate();
if (updateQuery != 0) {
out.println("Successful Registration");
}
}
catch (Exception ex) {
out.println("Unable to connect to database.");
}
finally {
// close all the connections.
ps.close();
con.close();
}
%>
</body>
</html>
Have you included driver jar file in your project ?
At String connectionURL = "jdbc:mysql://localhost:3306/table"; is table is your database name which you want to connect?
At
catch (Exception ex) {
out.println("Unable to connect to database.");
}
include ex.printStackTrace() which will show you exact error.
Well... "unable to connect to database" means exactly that. Your JSP could not connect to the database.
Please add the full stack trace (error) in your question. That way it will be clearer what the problem is.
Off the top of my head, the possible culprits are:
You don't have the driver loaded in your JEE container. Did you add the database driver?
Your driver is not properly configured. Did you specify the correct "driver class" when adding the driver?
Your URL is wrong. Please check the value of the URL. Is it well-formed? Follow the exact format as the example one and insert your specific values.
There's no database actually running at that HOST:PORT. Was the database created?
Your credentials are wrong, disabled, or don't even exist yet. Check your username and password with your DBA. Do you have the right ones?
So, if you have checked already that and you think you have all those good, check the connection using a standalone client first. That way you'll see if the connection can be established. I would recommend Squirrel SQL Client or Eclipse's Data Source Explorer. Give them a try to check you have the right parameters.
Once you check your connection with a local client, everything should work in the JEE container.

How do I connect to MySQL Database located on a Namecheap server through java jdbc?

Packet for query is too large (4739923 > 1048576).
You can change this value on the server by setting the max_allowed_packet' variable.
This error is the end of me. On the server I'm trying to access, this max_allowed_packet is much larger than 1,048,576.
I have had a hell of a time solving this issue, resorting to as many forums as possible. It should be pretty simple. I want to connect to MySQL database on my namecheap server from a Java program on my computer. I have the IP address, the port for ssh. I can access the database totally and query from mySQL Workbench.
Here is my code
package testingdb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.JSch;
import com.mysql.jdbc.Driver;
public class DatabaseTesting {
public static void main(String[] args) {
String huser = "user";
String hpass = "*********";
String userName = "username_user";
String password = "*********";
String host = "<My web server>";
String url = "jdbc:mysql://<My Web Server>:<port>/";
Session session= null;
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session = jsch.getSession(huser, host, <port>);
session.setConfig(config);
session.setPassword(hpass);
session.connect();
System.out.println("Connected through SSH");
session.setPortForwardingL(3306, "127.0.0.1", <port>);
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Logging into Database: "+ userName);
Connection con = DriverManager.getConnection(url, userName, password);
System.out.println("Server connected successfully");
//Statement st = con.createStatement();
//ResultSet results = st.executeQuery("SELECT * FROM NPC_DATA");
//System.out.println(results);
}
catch(Exception e) {
System.out.println("connection failed . . .");
System.out.println(e.getMessage());
}
}
}
My hpass and user and that are all correct when I type them in (I hid them for obvious reasons) I'm not sure what could go wrong. Help told me that Namecheap does not run with Java, but should this matter if my client is using JAVA to connect to the Server? Thank you so much.
Could you try to change these lines?
session.setPortForwardingL(<local port>, "<My web server>", <remote port>);
This will create a local port listening to remote port on your webserver. Now you need to make connection with your local port so url will change to:-
String url = "jdbc:mysql://localhost:<local port>/";

java.sql.SQLException: No suitable driver found for localhost test [duplicate]

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 7 years ago.
When trying to connect to mysql I always get this error:
java.sql.SQLException: No suitable driver found for localhost test
I already included the mysql-connector.jar in the /WEB-INF/lib in my app. What else do I need to configure to make it work? Do I need to add something in web.xml? I'm not using the appengine.
Here is my code in the server:
package com.mysql.server;
import java.sql.Connection;
import java.sql.DriverManager;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.mysql.client.ConnDb;
public class ConnDbImpl extends RemoteServiceServlet implements ConnDb {
public Connection con;
#Override
public String tryConn() {
try{
String host = "localhost";
String db = "test";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "pwd";
Class.forName(driver).newInstance();
con = DriverManager.getConnection(host+db, user, pass);
return "Connected to Database";
} catch(Exception ex) {
return ex.toString();
}
}
}
You will get this exception when the JDBC URL is not accepted by any of the loaded JDBC drivers as per the Driver#acceptsURL() method. You actually forgot the JDBC driver specific URI prefix. For the MySQL JDBC driver this is jdbc:mysql://. The full connection URL should look like this:
con = DriverManager.getConnection("jdbc:mysql://localhost/test", user, pass);
See also:
Connector/J documentation - Obtaining a connection
I found another cause for this error message. In my case the user simply had no privilege to the database e.g. to the selected table. Dear driver developers, why do you use such misleading error messages? A lot of people have real trouble with this.
For me, it was forgetting to include the MySQLJDBC Driver in the project libraries. DOH!
This was giving that error:
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/lib_db","root","root");
but when I changed that to:
Connection connection =DriverManager.getConnection("jdbc:mysql://localhost/db_name?"+"user=root&password=root");
error was gone

Hey need help with a mysql exception i am getting abt communication link failure

Hey guys, i m running a mysql server on my host machine.
The code is provided below.When i try 2 run the same code from another machine connected to the same router.I get the exception that I hav provided below the code.
Please help.
Code:-
import java.sql.;
import java.io.;
public class Login{
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Connection conn = null;
String url = "jdbc:mysql://"+br.readLine()+":3306/";
String dbName = "p2p";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "123";
System.out.println("Please input Username:");
String user=br.readLine();
System.out.println("Please input Password:");
String pass=br.readLine();
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String sql="select password from newuser where username='"+user+"'";
Statement stmt=null;
ResultSet rs=null;
try{
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
if(rs.next())
{
if(rs.getString("password").equals(pass))
System.out.println("true");
else
System.out.println("false");
}
else System.out.println("false");
}
catch(Exception e){System.out.println(e);}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Exception:-
com.mysql.jdbc.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driv
er has not received any packets from the server.
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1
112)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:346)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2334)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2
371)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2163)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:794)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:374)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java
:305)
at java.sql.DriverManager.getConnection(DriverManager.java:525)
at java.sql.DriverManager.getConnection(DriverManager.java:171)
at Login.main(login.java:20)
Caused by: java.net.UnknownHostException: 192.168.1.23306: 192.168.1.23306
at java.net.InetAddress.getAllByName0(InetAddress.java:1128)
at java.net.InetAddress.getAllByName0(InetAddress.java:1098)
at java.net.InetAddress.getAllByName(InetAddress.java:1061)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.ja
va:244)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:295)
... 9 more
Are the machines on the same network or allowed in the same VLAN. The error that you are getting means the program cannot even see the MySQL server. Another possibility, check the account on MySQL and make sure that the both servers are in the allowed HOSTS for the account.
Your stack trace has this line:
java.sql.DriverManager.getConnection(DriverManager.java:171) at Login.main(login.java:20) Caused by: java.net.UnknownHostException: 192.168.1.23306: 192.168.1.23306 at
Which means your Java process doesn't know about host address 192.168.1.23306
Hey guys, i got the error.
Instead of using br.readLine() when i put the actual ip of the mysql server m/c the program runs.