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 ;)
Related
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
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.
I'm fairly new to database management. I'm just trying to connect to the database and retrieve and display a table in the command prompt. The database is not on my computer. I am fairly certain that the url is the problem. The code:
import java.io.*;
import java.sql.*;
class transfer{
//driver and DB URLs
final static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
final static String DB_SQL = "jdbc:microsoft:sqlserver://localhost:1433;" + "database=DataDB;" + "user=sa;" + "password=1234";
//Database Username and password
final static String user1 = "sa";
final static String pass1 = "1234";
static ResultSet rs;
public static void main(String args[]) throws SQLException, ClassNotFoundException{
Connection conn_sql = null;
Statement stmt_sql = null;
//Statement stmt_ora = null;
//Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Open Connection
System.out.println("Connecting to SQL database...");
conn_sql = DriverManager.getConnection(DB_SQL, user1, pass1);
//Execute Query
String sql_query;
System.out.println("Creating statement for SQL...");
stmt_sql = conn_sql.createStatement();
sql_query = "Select * from attendancesummary";
rs = stmt_sql.executeQuery(sql_query);
System.out.println("SQL table details");
System.out.println("Creating statement for SQL...");
while(rs.next()){
//Retrieve data
int cno = rs.getInt("CardNo");
int in_time = rs.getInt("entry");
int out_time = rs.getInt("Exittm");
String name = rs.getString("Name");
int date = rs.getInt("TrDate");
//Display data
System.out.print("Employee ID: "+cno);
System.out.print("\tName: "+name);
System.out.print("\tDate:"+date);
System.out.print("\tEntry: "+in_time);
System.out.print("\tExit: "+out_time);
}
}
}
The database name is DataDB and the table that I want to retrieve and display is attendancesummary. I have set my path as "C:\Program Files\Java\jdk1.8.0_11\bin";"C:\Program Files\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc4.jar"
The code compiles fine.. but when I run it, I get the following error:
Exception in thread "main" java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run
at java.net.URLClassLoader$1.run
at java.security.AccessController.doPrivileged
at java.net.URLClassLoader.findClass
at java.lang.ClassLoader.loadClass
at sun.misc.Launcher$AppClassLoader.loadClass
at java.lang.ClassLoader.loadClass
at java.lang.Class.forname0
at java.lang.Class.forname
at transfer.main
I am truly lost. Any help would be appreciated!
It means that sqljdbc4.jar is missing from your CLASSPATH while running the code. If you are running this from command line then add the path to sqljdbc4.jar in -cp switch of java command.
If you are running from eclipse, then add sqljdbc4.jar in your build path.
Add sqljdbc4.jar in your classpath.
If you are using Eclipse then you can right click on project -> properties -> java build path.
Go to libraries and click on add external jar.
Then add the jdbc driver jar.
Hope this helps.
You have to add the JDBC driver to your project class path: example if you are using Eclipse put the jar in the 'lib' folder
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.
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.