I'm reading through the JDBC API Tutorial and Reference 3/E (MAN, what a dry tome), and I'm having trouble connecting my Java program to my MySQL database using the MySQL Connector supplied by Oracle.
I've placed it in my folder
C:\Windows\Sun\Java\mysql-connector-java-5.1.24
and I've pointed my Workspace CLASSPATH in JGrasp to
C:\Windows\Sun\Java\mysql-connector-java-5.1.24\mysql-connector-java-5.1.24-bin.jar
I'm trying to connect to a database called "Coffee." It definitely exists:
mysql> show databases;
+---------------------+
| Database |
+---------------------+
| information_schema |
| coffee |
| mysql |
| performance_schema |
| phpmyadmin |
+---------------------+
5 rows in set (0.03 sec)
here's my Java code. (If you have the book, I'm on page 88. The only difference between my code and theirs is some comments, and that I'm going with MySQL.)
//first, import sql package
import java.sql.*;
//name class CreateCoffees
public class CreateCoffees {
public static void main(String[] args){
String url = "jdbc:mysql://127.0.0.1:coffee";
//declare variables
Connection conn;
String createString = "create table COFFEES " +
"(COF_NAME varchar(32), " +
"SUP_ID int, " +
"PRICE float, " +
"SALES int, " +
"TOTAL int)";
Statement stmt;
//instructions
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(java.lang.ClassNotFoundException cnfe){
System.out.println("Class Not Found - " + cnfe.getMessage());
}
try{
conn = DriverManager.getConnection(url, "root", "");
stmt = conn.createStatement();
stmt.executeUpdate(createString);
stmt.close();
conn.close();
}
catch(SQLException sqle){
System.out.println("SQL Exception: " + sqle.getMessage());
}
}
}
Everything compiles just fine, but when I run it, I throw the following SQLException:
SQL Exception: Cannot load connection class because of underlying exception: 'java.lang.NumberFormatException: For input string: "coffee"'.
What exactly am I doing wrong? Is there something I can run to otherwise test connectivity between Java and the database? I'm fairly new to both.
Also, it should be noted that this is not homework.
EDIT: It would seem the offending line of code is
String url = "jdbc:mysql://127.0.0.1:coffee";
and should be changed to
String url = "jdbc:mysql://127.0.0.1/coffee";
because coffee is a database and not a port.
I guess I need more of it. Thanks to everyone who helped.
Your connection URL is using coffee as the port. You should use something like:
jdbc:mysql://127.0.0.1:3306/coffee
Why do you have "coffee" as your port number? You're supposed to have your mysql server port number there
jdbc:mysql://127.0.0.1:coffee
Hint: default port number is 3306. So try
jdbc:mysql://127.0.0.1:3306/coffee
(Assuming your database name is coffee)
I think the parser is getting confused and thinking that coffee is a port number.
Try this:
jdbc:mysql://127.0.0.1/coffee
Related
I am working on a simple mariaDB database called movieDB and there is a mariaDB user called customerAgent. I know there are many similar on StackOverflow, but I am not using a root account, but a normal account with minimum granted privileges.
I can access the database movieDB in terminal via SSH like this:
[root#myServer]# mysql -ucustomerAgent -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 102
Server version: 10.2.12-MariaDB MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> USE movieDB;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [movieDB]> show grants;
+----------------------------------------------------------------------------------------------------------------------------+
| Grants for customerAgent#localhost |
+----------------------------------------------------------------------------------------------------------------------------+
| GRANT Customer_Role TO 'customerAgent'#'localhost' |
| GRANT USAGE ON *.* TO 'customerAgent'#'localhost' IDENTIFIED BY PASSWORD '*23AE809DDACAF96AF0FD78ED04B6A265E05AA257' |
| GRANT USAGE ON *.* TO 'Customer_Role' |
| GRANT SELECT ON `movieDB`.* TO 'Customer_Role' |
| GRANT SELECT, INSERT ON `movieDB`.`orders` TO 'Customer_Role' |
+----------------------------------------------------------------------------------------------------------------------------+
5 rows in set (0.00 sec)
MariaDB [movieDB]> select current_role();
+----------------+
| current_role() |
+----------------+
| Customer_Role |
+----------------+
1 row in set (0.00 sec)
MariaDB [movieDB]>
But when I execute JDBC codes on localhost, access is denied at the line stmt.execute("USE movieDB");:
Access denied for user 'customerAgent'#'localhost' to database 'movidDB'
The java JDBC codes are: (I have removed some unnecessaries in the class, but in the case that I missed anything important, please do point out!)
import java.sql.*;
import java.util.*;
Class movieDBFoundation {
static private String DBServerAddress = "localhost";
static private Connection conn;
static private String getDBServerAddress() {
return DBServerAddress;
}
public static void main(String[] args) {
System.out.println("Connection started.");
if(DBConnect()) {
System.out.println("Connection succedded.");
}
else {
System.out.println("Connection failed.");
return;
}
}
static private Boolean DBConnect() {
String connectString = "jdbc:mysql://" + getDBServerAddress() + ":3306/"
+ "?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&&useSSL=false";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(connectString, "customerAgent", "123");
System.out.println("Connection reached.");
Statement stmt;
stmt = conn.createStatement();
String SQL = "USE movidDB";
stmt.execute(SQL);
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return false;
}
}
Some answers in similar questions say JDBC need all privileges on a database, but that does not sound very safe nor secure. Is it a must to have all privileges to achieve what I am trying to do here?
Your problem is that the database movidDB don't exist. Should it not be movieDB?
How can get the name of the database name from connection object
try {
this.ds = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/amger");
} catch (NamingException ne) {
}
Connection conObj = ds.getConnection();
How do I get that Database name from con
Probably the most straightforward way to get the database name from the JDBC Connection object itself is via the getCatalog() method:
Connection#getCatalog()
However, as Konstantin pointed out in his comment below, that value will not change if the current MySQL database is changed by issuing a USE dbname statement.
getCatalog() might still be useful in an application that
does not change databases, or
does things "The JDBC Way" by using setCatalog() to change the current database,
but for MySQL, using SELECT DATABASE() appears to be safer overall.
Note also that this potential discrepancy between getCatalog() and the actual current database depends on the behaviour of the particular JDBC driver. Out of curiosity I tried something similar with the Microsoft JDBC Driver 4.0 for SQL Server and .getCatalog() was indeed aware of the change to the current database immediately after running a USE dbname statement. That is, the code
String connectionUrl = "jdbc:sqlserver://localhost:52865;"
+ "databaseName=myDb;" + "integratedSecurity=true";
try (Connection con = DriverManager.getConnection(connectionUrl)) {
System.out.println(String.format(
"getCatalog() returns: %s",
con.getCatalog()));
try (Statement s = con.createStatement()) {
System.out.println(" Executing: USE master");
s.execute("USE master");
}
System.out.println(String.format(
"getCatalog() returns: %s",
con.getCatalog()));
} catch (Exception e) {
e.printStackTrace(System.out);
}
produced the following results:
getCatalog() returns: myDb
Executing: USE master
getCatalog() returns: master
If you know that DB is Mysql you could just perform SELECT DATABASE() on your connection and read the resulset with current database name in it.
Here is description of DATABASE function.
Let's assume you used url as "jdbc:mysql://localhost/test"
Then do the following:
DatabaseMetaData dmd = connection.getMetaData();
String url = dmd.getURL();
System.out.println(url.substring(url.lastIndexOf("/") + 1));
Run
System.out.println(connection.getMetaData().getURL());
Paste the output in notepad
search the value for 'databaseName=yourDBName'
I have Access DB ( mdb file) to which I can connect using my java program. User level security for the Access DB is on. I am trying to add new user in the User level security i.e. MDW file.
I think this can be done by executing SQL statement = Microsoft Jet 4.0 SQL commands = "CREATE USER Boyd password"
but when i execute it with, it give me error which is as follows:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in CREATE TABLE statement.
Anyone can help me?
Thanks in Advance.
The following code works for me:
import java.sql.*;
public class JDBCQuery {
public static void main( String args[] )
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=C:\\Users\\Public\\uls\\ulsTest.mdb;" +
"SystemDB=C:\\Users\\Public\\uls\\Security.mdw;" +
"Uid=Gord;" +
"Pwd=obfuscated;" +
"ExtendedAnsiSQL=1;");
Statement s = conn.createStatement();
s.execute("CREATE USER Tim pwd");
System.out.println("User 'Tim' created.");
s.execute("DROP USER Tim");
System.out.println("User 'Tim' dropped.");
s.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
I'm on a mac, running a MAMP instance of MySQL. I'm trying to use a jdbc driver to connect my java code to a database called 'test', working with a table called 'customer.' I keep getting an error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8889/test
I'm not sure if the problem is with my code, or if it's a configuration problem with the MAMP instance of MySQL, or if it's something else entirely.
I have an initialize driver method:
public void initializeDriver(){
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println(e.toString());
}
}
And I have a connection created in the following way:
public void insertCustomer(String connectionUrl, String connectionUser, String connectionPassword, Customer customer) {
try{
Connection conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
Statement constat = conn.createStatement();
String query = "INSERT INTO customers (customer_id, email, deliverable, create_date) VALUES (" + customer.id + ", " + customer.emailAddress + ", " + customer.deliverable + ", " + customer.createDate + ")" ;
constat.executeQuery(query);
conn.close();
}
catch(SQLException e){
System.out.println(e.toString());
}
}
And I have downloaded mysql-connector-java-5.1.20 and set it in my classpath.
If anyone has any suggestions for how I could correct this error, I would be really grateful!
You have to put MySQL jdbc connector jar library into the classpath.
Then initialize the driver before opening the connection with code like the following :
Class.forName("com.mysql.jdbc.Driver").newInstance();
You will need the corresponding mysql JDBC driver jar in your classpath or loadable by your container. See the doc for ConnectorJ and note the installation instructions.
Try to add mysql-connector-java-5.1.20.jar to Glassfish (or Tomcat) lib folder.
you have also a error in this row
constat.executeQuery(query);
if you want insert some data in data base you have to use this code
constat.executeUpdate(query);
I installed MySql on my own machine. I created database, create table, ... using MySql CommandLine Client. When working on a project in school, I connected to school's database using this syntax:
public static Statement connect() {
try {
Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
conn = DriverManager.getConnection( "1", "2", "3" );
stmt = conn.createStatement();
}
catch( Exception e ) {
System.out.println( "Connection Error: " + e );
}
return stmt;
}
In my local machine, I don't have to type in user name, all I did is just login with my password as root user:
Enter password: ****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.1.53-community MySQL Community Server (GPL)
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use chandb;
Database changed
mysql> show tables;
+------------------+
| Tables_in_chandb |
+------------------+
| another |
| cars |
| employees |
+------------------+
3 rows in set (0.03 sec)
mysql> select * from Another;
+----+-----------+----------+
| Id | GoldValue | Model |
+----+-----------+----------+
| 0 | 100 | Civic DX |
+----+-----------+----------+
1 row in set (0.00 sec)
mysql>
I would like to know how can I connect to my local machine's database? what should I put as parameters within method .getConnection
conn = DriverManager.getConnection(
"1", // ?
"2", // ?
"3" ); // ?
Best regards,
Chan
Simple Connection:
import java.sql.Connection;
import java.sql.DriverManager;
public class Main {
public static void main(String[] argv) throws Exception {
String driverName = "org.gjt.mm.mysql.Driver";
Class.forName(driverName);
String serverName = "localhost";
String mydatabase = "mydatabase";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "username";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
}
}
It looks like you left your username and password in the source you posted.
I don't see why you can't just do
DriverManager.getConnection("jdbc:mysql://localhost/chandb", "user, "pass");