Cant connect to my SQL database - java

So I'm having an issue connecting to MySQL with Java.
Heres my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBAccess {
private String Host;
private String User;
private String Password;
public DBAccess() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Password = "password";
Host = "jdbc:mysql://localhost/worlddb";
User = "root";
#SuppressWarnings("unused")
Connection connect = DriverManager.getConnection(Host,User,Password);
System.out.println("Connected!");
}
public void RetreiveData(){
}
public void ChangeData(){
}
}
The error that I'm getting is Exception in thread "main"
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'worlddb'
http://postimg.org/image/593stjvjx/
in mySQL workbench, my connection name is "worlddb"
hostname is Liquidus(which is the localhost)
socket is MySQL
Port: 3306
Why is this?

There is a difference between name of connection and name of Database,try world, test or sakila from schemas in the picture.

connection = DriverManager.getConnection("jdbc:mysql://localhost/worlddb?" +"user=root&password=password");
Try this, I have a connection to mysql db with same connection, you just add ? after the name of the db.

Try this it's hopeful for you:
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection("jdbc:mysql://localhost/worlddb","root","password");

Make sure that the database what you have mentioned in Host = "jdbc:mysql://localhost/worlddb"; i.e worlddb is correct or not.
The name of the database here is CASE SENSITIVE! So, if you try to connect using a database name like "test2" instead of "Test2" , you will get the
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'test2'
Also try using port number too
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/worlddb", "root", "password");

In the above code, port number is missing.
connection = connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/worlddb","root", "password");
default port number of mysql is 3306

Take care to not have white spaces and use jdbc:mysql://localhost:3306/dbname

Are you sure that the DB server is not case sensitive? I mean maybe on the DB server the DB name is WorldDb and you are trying to connect to it by using worlddb (all low lecters)..
Try to use the same name or to configure MySQL to be case insensitive

Write
"jdbc:mysql://localhost:3306/worlddb"
instead of
"jdbc:mysql://localhost/worlddb"

Charaf jra was right i had the same issue.
your schema(schema = Database) is listed as Host = "jdbc:mysql://localhost/worlddb";
If you look at the schemas in the pic you posted https://postimg.cc/image/593stjvjx/
the schema(Database) is world.

Related

Can't get the connection to MariaDB

I would like to use my MariaDB database but I get the error message:
java.lang.ClassNotFoundException: org.mariadb.jdbc.Driver
My pom.xml includes:
<dependencies>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>1.1.7</version>
</dependency>
</dependencies>
Also I have downloaded the file mariadb-java-client-2.4.1-sources.jar and placed it into WEB-INF/lib.
Database.java
package ch.yourclick.zt;
import java.sql.*;
public class Database {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// Ensure we have mariadb Driver in classpath
Class.forName("org.mariadb.jdbc.Driver");
// create our mysql database connection
String host = "localhost";
String dbname = "zt_productions";
String url = "jdbc:mariadb://" + host + "/" + dbname;
String username = "root";
String password = "test";
Connection conn = DriverManager.getConnection(url, username, password);
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String query = "SELECT * FROM users";
// create the java statement
Statement st = conn.createStatement();
st.close();
}
}
I also tried it with Class.forName("org.mariadb.jdbc.Driver").newInstance();.
No matter what I try, I always get the same error message. Any help would be appreciated.
You are using the wrong jar file. The source won't help you out.
Instead of mariadb-java-client-2.4.1-sources.jar, try using mariadb-java-client-2.4.1.jar.
I had this Problem myself:
the solution was quite simple... MariaDB is basically still MySQL. In the Url you are using to connect to the Database (jdbc:mariadb://localhost:3306) you can therefore just use jdbc:mysql://localhost:3306 <- i just replaced mariadb with mysql. It is still running on a mariadb server but it works so dont change it ;)

"Could not create connection to database server" netbeans google cloud sql error

I am trying to create my first API using java httpServlet and netbeans which will be connected to a database on google cloud based its examples and documentations. I have not created the database, but I was given the necessary credentials and vars to create the connection. So I have downloaded the project from github, and when I tried to open it from netbeans there was some issues concerning dependencies ... So I resolved them, I replaced the credentials with their values and run the project; Unfortunately an error was thrown: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. I made some searches but did not get any result... Could it be an error from this code ? an error from database security if it was invisible on cloud? Any help is more than appreciated.
public class ListTables {
public static void main(String[] args) throws IOException, SQLException {
String instanceConnectionName = "<foo:foo:bar>";
String databaseName = "myDatabaseName ";
String username = "myUsername ";
String password = "<myPass>";
if (instanceConnectionName.equals("<insert_connection_name>")) {
System.err.println("Please update the sample to specify the instance connection name.");
System.exit(1);
}
if (password.equals("<insert_password>")) {
System.err.println("Please update the sample to specify the mysql password.");
System.exit(1);
}
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
databaseName,
instanceConnectionName);
try{
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
/* try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("select * from wf_accounts;");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}*/
}catch(Exception ex){
System.out.println("Error: " + ex.toString());
}
Update
Same error was thrown when I did this:
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
"",
"");
Any hints?
First you have to check whether the mysql server is running on.If you are Windows user you can simply
Go to Task Manager
Go to Services
then search for your Mysql server(eg:for my case its MYSQL56)
then you will see under the status column it says its not running
by right clicking and select start
If it's already running then you have to do as in mysql Documentation,
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property
autoReconnect=true
to avoid this problem

Java Connection String to Oracle Cloud Database

I had problem when connecting to Oracle Cloud Database from java code.
I have no problem connecting other non-cloud oracle databases.
I can connect to the Oracle Cloud Database with sql tools, except from the java codes.
The hostname, username and password is correct one, i don't reveal the real username and password.
Error: java.sql.SQLException:
SQLException: SQLState(null) vendor code(17002)
java.sql.SQLException: Io exception: Oracle Error ORA-12650: No common encryption or data integrity algorithm
My code as following:
String dbURL = "jdbc:oracle:thin:#192.133.133.23:1521:ORCL";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(dbURL, "username1", "password");
}catch(Exception)
{
e.printStacktrace();
}
/**
* The below one is for oracle thin client
Its worked for the ojdbc6 driver.
*/
public Connection conCheck() {
Connection con=null;
try { //step1 load the driver class
Class.forName("oracle.jdbc.OracleDriver");
Properties props = new Properties();
props.put("oracle.net.encryption_client", "REQUIRED");
props.put("oracle.net.encryption_types_client", "( " + AnoServices.ENCRYPTION_AES256 + "," +AnoServices.ENCRYPTION_AES192 + ")");
props.put("oracle.net.crypto_checksum_types_client", "( SHA1 )");
props.put("user", "username");
props.put("password","password");
//step2 create the connection object
con=DriverManager.getConnection( "jdbc:oracle:thin:#host:port:serveiceid",props);
System.out.println("Con"+con);
}catch(Exception e) {e.printStackTrace(); }
return con;
}
Seems like changing syntax in your connection string to lookup SERVICE_NAME instead of SID must help you connect your database.
String dbURL = "jdbc:oracle:thin:#192.133.133.23:1521/ORCL";
Additional Read : Thin-style Service Name Syntax
If this as well doesn't help, then would suggest to add below 2 lines to your sqlnet.ora in database.
SQLNET.CRYPTO_CHECKSUM_TYPES_CLIENT= (SHA1)
SQLNET.CRYPTO_CHECKSUM_CLIENT = requested
First mandatory check is to verify the oracle jdbc version. if you use incompatible version,we will get this kid of errors.

How to specify path to mySQL using localhost?

I have been having issues specifying the path (I have two files: comments.frm and db.opt in the following folder: C:\xampp\mysql\data\feedback)... I am using XAMPP and mySQL. I am not sure why I am having an error? Please, take a look this part of my code:
public void readDataBase() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost//feedback"
+ "user=root&password=1234");
PS: My password for localhost is 12345678
You should try
DriverManager.getConnection("jdbc:mysql://localhost/feedback", "root", "1234");
For better clarity you can use the other overloaded method while getting connection.
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://<db_ip>/<db_name>",
"<username>", "<pwd>");
Try
connect = DriverManager
.getConnection("jdbc:mysql://localhost/feedback?user=root&password=1234")
(you forgot about the question mark after "feedback")
Many answers but everyone forgot the port of the database.
If you use mysql then try 3306 as db port.
http://www.petefreitag.com/articles/jdbc_urls/ - list of jdbc urls (Examples)
try
{
conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName, user, passwd);
}
catch(SQLException sqle)
{
System.out.println("Connection fails: " + sqle.getMessage());
}
I think you need to use this:
DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback", "root", "1234");
I check my old project and find that I don't use double slash here /feedback.
also you can specify encoding like this :
DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback?characterEncoding=UTF-8&characterEncoding=Cp1251", "root", "1234");
and also one more advice. Don't use hard code. Get url, password and user name from property files.
Try this hope it can help you!!!
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/feedback?"+"user=root&password=1234");
also see the URL Mistakes like:
jdbc:mysql://localhost//feedback?
// after localhost... check and try my code...
.

Get the metadata for prepared statement in java with MySql DB

I want to fetch parameter name and parameter type of given prepared statement. I am using MySQL Database. But when I run my program it is throwing an error:
Exception in thread "main" java.sql.SQLException: Parameter metadata not available for the given statement
at this line
String paramTypeName = paramMetaData.getParameterTypeName(param);
I don't know why this is happening. Please anybody help me if possible.
Here's my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getMySqlConnection();
Statement st = conn.createStatement();
String query = "select * from survey where id > ? and name = ?";
PreparedStatement pstmt = conn.prepareStatement(query);
ParameterMetaData paramMetaData = pstmt.getParameterMetaData();
if (paramMetaData == null) {
System.out.println("db vendor does NOT support ParameterMetaData");
} else {
System.out.println("db vendor supports ParameterMetaData");
// find out the number of dynamic parameters
int paramCount = paramMetaData.getParameterCount();
System.out.println("paramCount=" + paramCount);
System.out.println("-------------------");
for (int param = 1; param <= paramCount; param++) {
System.out.println("param number=" + param);
String paramTypeName = paramMetaData.getParameterTypeName(param);
System.out.println("param SQL type name=" + paramTypeName);
}
}
pstmt.close();
conn.close();
}
public static Connection getMySqlConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
}
According to this
Should the driver generate simplified parameter metadata for PreparedStatements when no
metadata is available either because the server couldn't support preparing the statement, or
server-side prepared statements are disabled?
You have to set generateSimpleParameterMetadata to true
use a connection string similar to this
jdbc:mysql://localhost:3306/mydb?generateSimpleParameterMetadata=true
MySQL JDBC driver currently does not support it. I am solving the similar issue and came up with the following workaround:
include H2 database in your project (it can also run in embedded mode or in-memory)
translate your MySQL create database script to H2 syntax (or write it in ANSI so it is compatible with both)
compile prepared statements on H2 database first and get metadata from them - H2 database supports this function and SQL query syntax is similar in most cases - then save the obtained meta information for later use
there might be differences in data types, etc, but in general this should give you about 80% match with MySQL without too much hassle
I know it has much caveats, but it might work in some use cases.
Also consider upgrading MySQL database to 5.7, there are some enhancements related to prepared statements which may help, but I am not very deeply knowledgable about those:
http://dev.mysql.com/doc/refman/5.7/en/prepared-statements-instances-table.html
http://dev.mysql.com/doc/refman/5.7/en/prepare.html
You have not set the parameter to the prepared statements, without which you cannot get parameter metadata. so first set the parameter
pstmt.setInt(val)
pstmt.setString(val)
After adding the parameters you can get the meta data about the parameter.
Hope this helps.

Categories

Resources