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");
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?
i wanted to connect to mysql from java code where mysql is in another system.
i have created a user in another machine "nilotpal".
Other machine address is 192.168.92.93.
I am able to ping to this machine. where am i missing?? can someone help?!!
The program i am using is:
import java.sql.*;
public class FirstExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://192.168.92.93:3306/tution";
// Database credentials
static final String USER = "nilotpal";
static final String PASS = "nilotpal";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Reference from Connect to mysql on a different server
Also make sure that mysql user nilotpal have remote connection permission. Other wise mysql-server will not allow your nilotpal user to login remotely. i.e. from your server (from program).
You can make sure that from mysql.user table.
mysql> select Host,User from user where User = "root";
+------------+------+
| Host | User |
+------------+------+
| 127.0.0.1 | root |
| ::1 | root |
| localhost | root |
| sgeorge-mn | root |
| % | root |
+------------+------+
4 rows in set (0.01 sec)
% means any host.
To create a user with remote connection permission, use following mysql query:
mysql> CREATE USER 'nilotpal'#'%' IDENTIFIED BY 'nilotpal';
First ping the machine using ping command, If it is pinging than check for the mysql user permission.
Granting Permission to user:
CREATE USER 'newuser'#'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'#'localhost';
FLUSH PRIVILEGES;
I am using MySQL 5.1 for my database and I'm sending the commands via a Java program (JBDC).
Is there a MySQL command for creating or altering a table?
Let's say I have a following table:
+----------+----------+
| column_a | column_b |
+----------+----------+
| value_a | value_b |
+----------+----------+
Now I want to use a command, that would add a column "column_c" if it didn't exist.
That would result in:
+----------+----------+----------+
| column_a | column_b | column_c |
+----------+----------+----------+
| value_a | value_b | |
+----------+----------+----------+
If the table didn't exist, it would create a new table with specified columns:
+----------+----------+----------+
| column_a | column_b | column_c |
+----------+----------+----------+
And finally, if the table had columns that weren't specified in the command, it would leave them untouched.
here is code in Java to create a table called Coffees:
/*Making the connection*/
try {//if any statements within the try block cause problems, rather than the program failing
//an exception is thrown which will be caught in the catch block
con = DriverManager.getConnection(url, "your username", "your password");
//create a statement object
stmt = con.createStatement();
//supply the statement object with a string to execute
stmt.executeUpdate("create table COFFEES (COF_NAME varchar(32), " +
"SUP_ID int, PRICE double, SALES int, TOTAL int, " +
"primary key(COF_NAME))");
//close the statement and connection
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
Explanation:
-In this example the java program interacts with a database that is located on a server, so we have to firstly we set the url of where the server is located and also sign in username and password, you may not be using the same method that I used.
-These need to be declared at the top of your java program:
String url = "jdbc:mysql://www.yoururlexample.co.uk";
Connection con;
Statement stmt
Hopefully this helps, you will then be able to insert data into the database and execute queries.
Edit:
This can be used in the executeUpdate statement if you want a table to be created if none exists with the name "COFFEES":
create table if not exists COFFEES
/*Making the connection*/
try {
//an exception is thrown which will be caught in the catch block
con = DriverManager.getConnection("jdbc:mysql:exaple.com", "username", "pass");
//create a statement object
stmt = con.createStatement();
//supply the statement object with a string to execute
stmt.executeUpdate("ALTER TABLE table_name ADD column_name datatype");
//close the statement and connection
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
I think that this is going to work for you.
Something like that might be a solution (this need at least one record in the table to work):
package com.stackoverflow.so20935793;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class App {
// complete this:
private static final String JDBC_URL = ".....";
private static final String JDBC_USER = ".....";
private static final String JDBC_PASS = ".....";
public static void main(final String[] args) {
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASS);
stm = con.prepareStatement("SELECT * FROM your_table LIMIT 1");
rs = stm.executeQuery();
if (rs.next() && rs.getMetaData().getColumnCount() == 2) {
// add your new column
}
} catch (final SQLException ex) {
// handle exception
} finally {
closeQuietly(rs);
closeQuietly(stm);
closeQuietly(con);
}
}
private static void closeQuietly(final AutoCloseable what) {
if (what == null) {
return;
}
try {
what.close();
} catch (final Exception ex) {
// ignore
}
}
}
(not tested)
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
How to fetch mysql cursor values in java program.
This is my mysql stored procedure
delimiter //
CREATE PROCEDURE cursor_student()
BEGIN
DECLARE row_count INT DEFAULT 0;
DECLARE exit_flag INT DEFAULT 0;
DECLARE sid varchar(30);
DECLARE sname varchar(50);
DECLARE rst CURSOR FOR
SELECT sid, sname FROM student WHERE class = '11th';
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET exit_flag=1;
OPEN rst;
fetch_loop: LOOP
FETCH rst INTO sid, sname;
IF exit_flag THEN
LEAVE fetch_loop;
END IF;
SET row_count = row_count +1;
END LOOP;
CLOSE rst;
SELECT 'number of rows fetched =', row_count;
END;
this is my simlpe java program to read above stored procedure
import java.sql.CallableStatement;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class StoredProcedure {
public static void main(String[] args) {
Connection dbConnection = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "test";
String driver = "com.mysql.jdbc.Driver";
ResultSet rs = null;
CallableStatement callableStatement = null;
String getDBUSERCursorSql = "{call cursor_student}";
try {
Class.forName(driver);
dbConnection = DriverManager.getConnection(url + db, "root", "");
try {
callableStatement = dbConnection.prepareCall(getDBUSERCursorSql);
callableStatement.executeUpdate();
rs = callableStatement.getResultSet();
while (rs.next()) {
System.out.println("sid "+rs.getString(1) +" name "+rs.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output of above java program is
sid number of rows fetched = name 6
but i want to display values of sid and sname
+------+-------+
| sid | sname |
+------+-------+
| 1 | asdf |
| 2 | dff |
| 3 | gggg |
| 4 | tttt |
| 5 | mmmm |
| 6 | .uyy |
+------+-------+
I think there is problem with your SP.
Could you please make the changes accourding to this SP Example? I haven't execute but I think so
DROP PROCEDURE IF EXISTS mysql_cursor_example $$
CREATE PROCEDURE mysql_cursor_example ( IN in_name VARCHAR(255) )
BEGIN
-- First we declare all the variables we will need
DECLARE l_name VARCHAR(255);
-- flag which will be set to true, when cursor reaches end of table
DECLARE exit_loop BOOLEAN;
-- Declare the sql for the cursor
DECLARE example_cursor CURSOR FOR
SELECT name status_update
FROM employees
WHERE name = name_in;
-- Let mysql set exit_loop to true, if there are no more rows to iterate
DECLARE CONTINUE HANDLER FOR NOT FOUND SET exit_loop = TRUE;
-- open the cursor
OPEN example_cursor;
-- marks the beginning of the loop
example_loop: LOOP
-- read the name from next row into the variable l_name
FETCH example_cursor INTO l_name;
-- check if the exit_loop flag has been set by mysql,
-- if it has been set we close the cursor and exit
-- the loop
IF exit_loop THEN
CLOSE example_cursor;
LEAVE example_loop;
END IF;
END LOOP example_loop;
END $$
DELIMITER ;