java.sql.SQLException: No database selected - why? - java

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

Related

Java client cant connect to local mysql database?

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.

IJ can't find driver for JDBC

I'm sorry for my question but can't solve this problems myself. Read different topics here and tried to read tutuorials...
I have MySQL server v8, and trying to start simple example in java to get data from server.
I set up classpat as system variable, put here mysql-connector-java-8.0.13.jar. Comman echo %CLASSPATH% shows it properly. Also i put connector in all project folders xD (didn't help either).
import java.sql.*;
public class file_test {
// JDBC URL, username and password of MySQL server
private static final String url = "jdbc:mysql://localhost:3306/MySQL80";
private static final String user = "root";
private static final String password = "123";
// JDBC variables for opening and managing connection
private static Connection con;
private static Statement stmt;
private static ResultSet rs;
public static void main(String args[]) {
String query = "select count(*) from actor";
try {
// opening database connection to MySQL server
con = DriverManager.getConnection(url, user, password);
// getting Statement object to execute query
stmt = con.createStatement();
// executing SELECT query
rs = stmt.executeQuery(query);
while (rs.next()) {
int count = rs.getInt(1);
System.out.println("Total number of actors in the table : " + count);
}
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
} finally {
//close connection ,stmt and resultset here
try {
con.close();
} catch (SQLException se) { /*can't do anything */ }
try {
stmt.close();
} catch (SQLException se) { /*can't do anything */ }
try {
rs.close();
} catch (SQLException se) { /*can't do anything */ }
}
}
}
Problem is when i try to start projest, IJ says:
"C:\Program Files\Java\jdk-11.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA\lib\idea_rt.jar=63236:C:\Program Files\JetBrains\IntelliJ IDEA\bin" -Dfile.encoding=UTF-8 -classpath F:\work\program\file_test\out\production\file_test file_test
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/MySQL80
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at file_test.main(file_test.java:21)
Exception in thread "main" java.lang.NullPointerException
at file_test.main(file_test.java:38)
Process finished with exit code 1
I want to run this code from IJ and get data from DB as a result.

JDBC / MySQL: How to check if a database or relation exists when creating one, then print off an error if it does

I'm VERY new to JDBC and am trying to work on a project for a class. We are supposed to create a database and relations for said database. If the database or relations already exist, we are supposed to print a message notifying the user. I'm not really sure how to do that. This is what I have so far for my methods:
public static void createDatabase() throws Exception {
String createString =
"CREATE DATABASE IF NOT EXISTS companydb";
Statement stmt = null;
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/?autoReconnect=true&useSSL=false";
String username = "username";
String password = "password";
Class.forName(driver);
Connection con = DriverManager.getConnection(url, username, password);
stmt = con.createStatement();
stmt.executeUpdate(createString);
System.out.println("Database created.");
} catch (Exception e) {
System.out.println(e);
} finally {
if (stmt != null) { stmt.close();
}
}
}
And for creating an employee table (not all values are created yet, just a test run):
public static void createEmployeeTable() throws Exception {
String createString =
"create table if not exists employee" + "(Fname char(32) NOT NULL, " +
PRIMARY KEY(Fname)";
Statement stmt = null;
try {
Connection con = getConnection();
stmt = con.createStatement();
stmt.executeUpdate(createString);
System.out.println("Employee table created.");
} catch (Exception e) {
System.out.println(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
Also I realize creating a table like that might not be the most efficient way to make a relation, but it's just a work in progress right now. Thanks for any help anyone can provide!
Regardless of if the database and relations/tables already exist or not, it puts out the same output:
Database created.
Connected to database.
Employee table created.
Connected to database.
Department table created.
Connected to database.
Project table created.
Connected to database.
Works_On table created.
Break down your code to two steps.
Execute a select query on the table. If the table does not exist, this will definitely throw an error.
If the select does not throw an error you can go ahead and create the table.

mysql loading previous query data to present queries also

public class Sample {
public static void main(String[] args) {
Connection con;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost/cluster", "root",
"password");
PreparedStatement pst = con
.prepareStatement("INSERT INTO EMPLOYEE_DETAILS (EMPLOYEE_ID,NAME,SALARY,DEPARTMENT,MANAGER)VALUES(?,?,?,?,?)");
pst.clearParameters();
pst.setObject(1, 101);
pst.setObject(2, "sam");
pst.setObject(3, 1000000);
pst.setObject(4, "IT");
pst.setObject(5, "jord");
pst.execute();
System.out.println("values got updted-----");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
for the first time this query is working fine and data is getting loaded into MySql data base.But when i execute the same programme after changing the values also the database is loading previously loaded values again and again..
why this is happening..
got it,the problem is actually with eclipse itself.After making any changes to the eclipse is not saving the new copy automatically and when we try to compile it is compiling the old copy without any new changes.If i manually save the code after any changes it is working fine...

How can I insert data from a connection to other connection?

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

Categories