I´m using eclipse and want to connect to my mysql database. I am new to SQL and thats my first time I want to do something like this. I´ve created two methods, which should connect to a mysql database, which is running on my PC. The first method should create a connection :
public static Connection connectionSQL() {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/example";
String username = "example";
String password = "1111";
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("Connected!");
} catch(SQLException | ClassNotFoundException e) {
System.out.println("ERROR: Cant connect to database! "+ e);
}
return null;
}
the second should create a table :
public static void createTable() {
try {
Connection connection = connectionSQL();
PreparedStatement ps = connection.prepareStatement("CREATE TABLE IF NOT EXISTS scammerjail(id int NOT NULL AUTO_INCREMENT, Username String, Countdown int, PRIMARY KEY(id))");
ps.executeUpdate();
} catch(SQLException e) {
System.out.println("ERROR: Cant create Table! " + e);
}
finally {
System.out.println("Table created!");
}
}
But everytime I try to run my Code, I get the following message:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client
I´m using maven as build tool and my dependency and its version isnt wrong I think.
Related
So i am facing the following problem.
I have developed an web app that has the following connection to a SQL Server database. (db connection code attached)
public class DBConnection
{
private DatabaseMetaData dma;
private static Connection con;
private static DBConnection instance = null;
private static String security = "integratedSecurity=true;";
private DBConnection()
{
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
} catch (Exception e) {
System.out.println("Can not find the driver");
System.out.println(e.getMessage());
}
try{
con = DriverManager.getConnection("jdbc:jtds:sqlserver://<Machine>;databaseName=<DBName>; useNTLMv2=true;");
//set autocommit
con.setAutoCommit(true);
dma = con.getMetaData(); // get meta data
System.out.println("Connection to " + dma.getURL());
System.out.println("Driver " + dma.getDriverName());
System.out.println("Database product name " + dma.getDatabaseProductName());
}
catch(Exception e){
System.out.println("Problems with the connection to the database");
System.out.println(e.getMessage());
System.out.println(con);
}
}
public static void closeConnection()
{
try{
con.close();
System.out.println("The connection is closed");
}
catch (Exception e){
System.out.println("Error trying to close the database " + e.getMessage());
}
}
public Connection getDBcon()
{
return con;
}
public static DBConnection getInstance()
{
if (instance == null)
{
instance = new DBConnection();
}
return instance;
}
public static void startTransaction()
{ try{
con.setAutoCommit(false);
}
catch(Exception e){
System.out.println("fail start transaction");
System.out.println(e.getMessage());
}
}
public static void commitTransaction()
{ try{
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail commit transaction");
System.out.println(e.getMessage());
}
}
public static void rollbackTransaction()
{
try
{
con.rollback();
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail rollback transaction");
System.out.println(e.getMessage());
}
}
I am using a Tomcat 8 on InteliJ IDE for running the app and debugging. Which works fine. (DB connection is established)
The problem is that when i take the war file and deploy it in the same Tomcat Server i get no DB Connection. (No DB connection)
I have checked all the .jar files in the tomcat and the project and I have added all the needed files.
Can't seem to find what is causing this issue. Maybe there is someone who got stuck with the same issue
I can't get a proper undertanding what is causing this issue and how to fix it
**EDIT: Following I have added the error displayed when trying to load data
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is java.lang.NullPointerException
root cause
java.lang.NullPointerException
com.lifeletapp.business.dataLayer.DbLogIn.isValidUser(DbLogIn.java:27)
com.lifeletapp.business.HelloController.verifyLogin(HelloController.java:33)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
DbLogin class:
public class DbLogIn implements ILogIn
{
private Connection conn;
public DbLogIn()
{
conn = DBConnection.getInstance().getDBcon();
}
public Staff isValidUser(String userName, String password)
{
Staff staff = new Staff();
try {
String query = "SELECT * FROM Staff WHERE userName=? AND pass=?";
PreparedStatement preparedStatement = conn.prepareStatement( query );
preparedStatement.setString(1, userName);
preparedStatement.setString(2, password);
ResultSet resultSet = preparedStatement.executeQuery();
while( resultSet.next() ) {
staff.setUserID(resultSet.getInt("userID"));
staff.setfName(resultSet.getString("fName") );
staff.setlName(resultSet.getString("lName") );
staff.setUserName(resultSet.getString("userName") );
staff.setPass(resultSet.getString("pass") );
staff.setEmail(resultSet.getString("email") );
}
resultSet.close();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return staff;
}
}
This is more a config or server issue. Not a code issue.
As mentioned in the comments I have tested if var conn == null -> resulted true. And the connection dose not get nulled anywhere. Please view code. Then again the above code works when run from the InteliJ debugger.
So finally figured out what was the issue.
Why was it working on my IDE config:
1. I was using java JDK 1.7 as JAVA_HOME
2. I was using an older version of Tomcat as a build
3. In order to work with JDTS you need to extract the nlmauth.dll from the .jar archive and copy it to the configured env JDK(jdk1.7-->>bin->>copy here)
Why was it not working on Tomcat server:
1.I was using Tomcat 8.xxx
2.Tomcat 8.xx require JDk 8
3. In the JDK 8 i have not past the nlmauth.dll ( once i have done this everything was working)
In order to approach this issue the first clue will be looking into the tomcat server logs.
On my presumption this issue is prom to occur only when you have an Database connection establish via Integrated Security.
My presumption is related to the fact that in the tomcat log the main error that was denying the JDBC driver was based on the integrated security credentials.
Best of luck to you all out there.
I want to insert data from a table which connection is oracle to another table which connection is mysql. I use netbeans and jdbc driver.
Is it possible? I mean how can I do select data from A table (X connection) and insert B table (Y connection)
connection X = DriverManager.getConnection("jdbc:oracle:thin:#" + host__ + ":" + port__ + servic, props);
connection Y = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
conn.close();
Thank you.
Here is a small example that copies a database table to another database.
You just need two connections conf(rom) and cont(o). You will need to modify both getConnection parameters, table names and field types.
// Copy
Statement stf, stmt;
Connection conf, cont;
ResultSet rsf, rs;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.mysql.jdbc.Driver");
conf = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:" + databaseFrom, "user1", "passwd1");
try {
stf = conf.createStatement();
rsf = stf.executeQuery("select * from supplier order by sname");
// read from rsf write to rs!
cont = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + databaseTo, "user2", "passwd2");
stmt = cont.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("select * from supplier order by sname");
while (rsf.next()) {
rs.moveToInsertRow();
rs.updateInt(1, rsf.getInt(1));
rs.updateString(2, rsf.getString(2));
rs.updateString(3, rsf.getString(3));
rs.updateString(4, rsf.getString(4));
rs.updateInt(5, rsf.getInt(5));
rs.updateString(6, rsf.getString(6));
rs.updateInt(7, rsf.getInt(7));
rs.updateDouble(8, rsf.getDouble(8));
rs.updateString(9, rsf.getString(9));
rs.insertRow();
}
} catch (SQLException s) {
JOptionPane.showMessageDialog(this, "problem creating database " + s);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getStackTrace());
} finally {
if (stf != null) {
try {
stf.close();
stmt.close();
} catch (SQLException e) {
// handle Exception
}
}
if (conf != null) {
try {
conf.close();
cont.close();
} catch (SQLException e) {
// handle Exception
}
}
}
You can create two classes for different connection:
public class OracleConnectionManager {
public static Connection getOracleConnection() throws SQLException, ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = null;
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:oracle","username","password");
return connection;
}
}
public class MySqlConnectionManager {
public static Connection getMySqlConnection() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306:mysql","username","password");
return connection;
}
}
Now you can use these classes to get the specific connections and do whatever you want.
You can get the oracle database connection and get the oracle statement > Resultsset, iterate over it
and insert the data into mysql.
Please let me know in case more information is required.
Follow these steps:
Connect to the Oracle database with one data access class
Connect to the MySQL database with a different data access class
Read row(s) from a table in the Oracle database
Perform any column transformations
Write row(s) to a table in the MySQL database
Close the database connections
the last days I was trying to learn how to access mySQL databases via Java.
I am able to load the driver and get a connection to the database ( at least I think so, since I don't get an exception there..)
the code is:
import java.sql.*;
public class test
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver loaded...");
}
catch(ClassNotFoundException e){
System.out.println("Error in loading the driver..."+e);
System.exit(0);
}
try
{
Connection dbConnection= DriverManager.getConnection("jdbc:odbc:test","root","password");
System.out.println("Connection successful...");
Statement stmt = dbConntection.createStatement();
stmt.executeUpdate("create table Accounts ( name char(20) )");
}
catch(SQLException e)
{
System.out.println("database-ConnectionError: "+e);
System.exit(0);
}
}
}
When I execute it, it says:
driver loaded... Connection successful...
database-ConnectionError: java.sql.SQLException: [MySQL][ODBC 5.2(w) Driver][mysqld-5.5.31]No database selected
I really don't know the problem, because I thought the database is selected during the "getConnection" process....
I tried to select a database by adding this line:
stmt.executeUpdate("use test;");
after creating the Statement.
unfortunately it didn't work because I got another exception which said I should check on the syntax. I don't understand that either because in my commandline it works just fine...
I don't know if it is possible to use these type of commands via Java so if it isn't, please forgive my mistake.
I hope you can help me and I didn't miss the solution during my own search!
Already Thanks to all who reply and use their time on my problems!
ps. If I forgot to point out some important infos ( I don't think i did) please ask:)
edit: I also tried to create a new database during runtime
stmt.executeUpdate("CREATE DATABASE test;");
this actually works, but the database won't be selected either...
Before you can add a table, you first have to select a database.
you can create a new database with:
CREATE DATABASE database_name
you can connect to a specific database with:
String url = "jdbc:mysql://localhost/databasename";
String username = "test";
String password = "test";
Connection connection = DriverManager.getConnection(url, username, password);
Firstly, I am considering my answer to show you another better way for connection with MySQL Database, it's much easier and less nu-expected Exception(s).
You need to do some steps:
Download Connector/J and add it to your class path(if you are using an IDE there is add the .jar to the library, or there is many tuts on YouTube).
Create your database in your MySQL program.
See this example below example below I made for you demonstrates how to connect and execute queries on MySQL :
import java.sql.*;
public class MySqlConnection {
private String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
private String MYSQL_URL = "jdbc:mysql://localhost:3306/test";
private Connection con;
private Statement st;
private ResultSet rs;
public MySqlConnection() {
try {
Class.forName(MYSQL_DRIVER);
System.out.println("Class Loaded....");
con = DriverManager.getConnection(MYSQL_URL,"","");
System.out.println("Connected to the database....");
st = con.createStatement();
int c =st.executeUpdate("CREATE TABLE Accounts (Name VARCHAR(30))");
System.out.println("Table have been created.");
System.out.println(c+" Row(s) have been affected");
con.close();
} catch(ClassNotFoundException ex) {
System.out.println("ClassNotFoundException:\n"+ex.toString());
ex.printStackTrace();
} catch(SQLException ex) {
System.out.println("SQLException:\n"+ex.toString());
ex.printStackTrace();
}
}
public static void main(String...args) {
new MySqlConnection();
}
}
Here is your updated example, which works for me.
public static void main(String[] args) throws InstantiationException,
IllegalAccessException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("driver loaded...");
} catch (ClassNotFoundException e) {
System.out.println("Error in loading the driver..." + e);
System.exit(0);
}
try {
Connection dbConnection = DriverManager
.getConnection("jdbc:mysql://localhost/test?user=root&password=password");
System.out.println("Connection successful...");
Statement stmt = dbConnection.createStatement();
stmt.executeUpdate("create table Accounts ( name char(20) )");
} catch (SQLException e) {
System.out.println("database-ConnectionError: " + e);
System.exit(0);
}
}
Make sure you have added a proper mysql-connector to your build path. I used the: mysql-connector-java-5.1.24-bin.jar
static final String DB_URL = "jdbc:mysql://localhost:3306/sys";
Use database name in the URL.
It worked for me
i'm trying to connect with jdbc to a specific schema in mysql server, the schema name is mining
when i'm trying to connect i get access to all the DB and therefore the executing statements apply to all the schemes in my db instead only to "mining"
this is how i establish a connection:
public class Mining {
Connection conn;
void createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.conn = DriverManager.getConnection(
"jdbc:mysql://localhost/?currentSchema=mining","admin","admin" );
//I ALSO TRIED THIS: "jdbc:mysql://localhost/mining","admin","admin"
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
any thoughts?
thanks!
try,
private Connection connect = DriverManager
.getConnection("jdbc:mysql://localhost/mining?"
+ "user=admin&password=admin");
String databaseURL = jdbc:mysql://hostName:portNumber/schemaName?
Connection connectionObj = DriverManager.getConnection(databaseURL,userName,password);
I'm working on a web project and I recently installed postgres 9.1.1
The postgresql server is up and running. I can connect via psql as usual and everything is loaded and properly saved from a dump of the db I made from 8.5.
So I also downloaded the JDBC4 driver for 9.1 postgres version here:
http://jdbc.postgresql.org/download/postgresql-jdbc-9.1-901.src.tar.gz
I added it to the java build path using the project properties via eclipse.
This is the code I use to provide db connection to other classes (i.e. it's a singleton, I get a new connection only if the existing is either closed or null, from one object at a time only)
public abstract class DBConnection {
private static Connection connection = null;
public static void connect() {
try {
if (connection == null) {
String host = "127.0.0.1";
String database = "xxxxx";
String username = "xxxxx";
String password = "xxxxx";
String url = "jdbc:postgresql://" + host + "/" + database;
String driverJDBC = "org.postgresql.Driver";
Class.forName(driverJDBC);
connection = DriverManager.getConnection(url, username,
password); //line firing the class not found exception
} else if (connection.isClosed()) {
connection = null;
connect();
}
} catch (SQLException e) {
e.printStackTrace(System.err);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public static void disconnect() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
public static Connection getConnection() {
try {
if (connection != null && !connection.isClosed()) {
return connection;
} else {
connect();
return connection;
}
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE,
null, e);
return null;
}
}
#Override
public void finalize() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
}
As I wrote in the title when I run the project and a class asks for a connection to this class I always get a Class Not Found Exception, Since it apparently can't load the org.postgresql.Driver.class The driver is located in a subfolder of the project ~/lib/org.postgresql-9.1-901.jdbc4.jar and as I said added to the build path via eclipse project properties.
I'm also providing a sample query to let see the usual behavior of my classes to access the DBConnection:
public static final User validateUserCredentials(String id, String pswd) {
Connection connection = DBConnection.getConnection();
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE, (connection!=null)?"connection not null":"connection null");
Statement stmt = null;
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, "validating credentials for user: username : " + id + " password : " + pswd);
String sql = "Select * from fuser where id = '" + id + "'";
ResultSet resultset = null;
try {
stmt = connection.createStatement();
resultset = stmt.executeQuery(sql);
Logger.getLogger(Credentials.class.getName())
.log(Level.SEVERE, sql);
resultset.next();
String password = resultset.getString("pswd");
if (pswd.equals(password))
return new User(id, pswd);
} catch (SQLException ex) {
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE,
null, ex);
} finally {
if (stmt != null)
stmt = null;
if (resultset != null)
resultset = null;
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
}
connection = null;
}
}
return null;
}
I'm working on a web project and I recently installed postgres 9.1.1
...
I added it to the java build path using the project properties via eclipse.
That's the wrong way. That JAR has to be dropped straight in /WEB-INF/lib folder of the web project without fiddling with the Build Path in the project's properties. That folder is standard part of webapp's runtime classpath.
Unrelated to the concrete problem: you've a major design flaw in your DBConnection class. You've declared Connection as static which essentially makes your connection not threadsafe. Use a connection pool and never assign the Connection (nor Statement nor ResultSet) as a class/instance variable. They should be created and closed in the very same try-finally block as where you're executing the query. Further you've there also a SQL injection hole. Use PreparedStatement instead of concatenating user-controlled variables in the SQL string.
See also:
JDBC MySql connection pooling practices to avoid exhausted connection pool
Get database connection from a connection pool
Am I Using JDBC Connection Pooling?
Add this dependency in your pom:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1203-jdbc4</version>
</dependency>
The first thing I'd do is unpack the jar and confirm that the driver is really in there as org.postgresql.Driver. I notice when looking at jarfinder and related sites that there isn't a Postgres 9.x jar containing org.postgresql.Driver.