I am trying to connect to mysql on my laptop. using the code I have pasted below. I have added the CLASSPATH containing the full path of the file:
mysql-connector-java-5.1.37-bin.jar
and exported it.But I get persistently the mentioned error. Can somebody tell me, please, what I am missing that makes me to get this error message form my machine.
My machine is Fedora core 21, I am trying to execute the code under the user, and not root, and this is the code i am using and of course the static final variables "user" and "password" are not empty strings as they are here:
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";
// Database credentials
static final String USER = "";
static final String PASS = "";
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 connect ion
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
System.out.println("Creating database...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
}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 JDBCExample
I have really tried to include any related information that i could guess it is related. If more information is needed to answer the question I am willingly ready to provide.
the DB_URL should set the port and the database name of MySQL.
just like(windows):
jdbc\:mysql\://111.202.27.131\:3306/bridgeResultDatabase?characterEncoding\=utf8
Here bridgeResultDatabaseis the mysql database name, it works for me.
Hope it helps.
There are some mistakes above.
Update(I try in my windows and using root of mysql in Linux):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public static void main(String[] args) throws ClassNotFoundException, SQLException{
String JDBC_DRIVER="com.mysql.jdbc.Driver";
String DB_URL="jdbc:mysql://192.168.11.52/mysql";
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL,"root","111111");
Statement statement = conn.createStatement();
String hrappSQL = "CREATE DATABASE testDatabase";
statement.executeUpdate(hrappSQL);
}
And I create the database "testDatabase" successfully in my linux mysql.
Related
So I'm trying to connect my java code to mysql and when I run the code below nothing prints out not even the error. I'm following a YouTube tutorial and understand everything except where he is getting "jdbc:mysql:" from. Any help would be awesome thanks.
package ztestconnection;
import java.sql.*;
public class Test {
static String Username = "Klongrich";
static String Password = "********";
static String Connection = "jdbc:mysql://localhost:8080/hospital";
public static void main(String [] args){
Connection con = null;
try{
con = DriverManager.getConnection(Connection, Username, Password);
System.out.println("Connected");
} catch(Exception e){
System.out.println(e);
}
}
To connect java application with the mysql database mysqlconnector.jar file is required to be loaded.
1:- Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
//STEP 1. Import required packages
import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
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
Before you can open a connection, you need to load the specific driver class, like so:
try
{
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception ex)
{
// handle the error
}
This ensures that java.sql.DriverManager can find the driver class definition.
There's some good example code in the MySQL Connector/J documentation.
As for the jdbc:mysql: part of the DSN (Data Source Name), that's a standard syntax that tells the driver manager and the database that they're opening a JDBC connection to a MySQL database. It will be explained in the Oracle Java documentation.
And Tim has a good point about your variable names. Don't give a variable the same name as a class. Even if it doesn't confuse the compiler, it'll confuse the hell out of the maintenance programmer (you) about a week from now.
package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
Class.forName(driver); // load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static int countRows(Connection conn, String tableName) throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
} finally {
rs.close();
stmt.close();
}
return rowCount;
}
public static void main(String[] args) {
Connection conn = null;
try {
conn = getConnection();
String tableName = "hospital_status";
System.out.println("tableName=" + tableName);
System.out.println("conn=" + conn);
System.out.println("rowCount=" + countRows(conn, tableName));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
// release database resources
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Error --->
The method "getConnection" on the service class "WBSer_RwCnt.Rw_Count" uses a data type, "java.sql.Connection", that is not supported
When i compile it without creating it as webservice it works correctly
but when i make it as web service it gives output as
Output --->
WBSer_RwCnt.Rw_CountSoapBindingStub#121a412b
Please Help !
Next Try
So this is what i have done after what you have said even then it gives following errors
Exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
Message:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static int countRows() throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
System.out.println("ram");
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
try {
Class.forName(driver);
}
catch (ClassNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
// load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM hospital_status");
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
finally {
rs.close();
stmt.close();
conn.close();
}
return rowCount;
}
}
i have the added all jar files including the java mysql connectors
This is not going to be a full answer as I'm not exactly sure about the tools you are using to compile the web service, but anyway, here goes:
Basically, a connection is something that is only valid on a particular machine. If it's a TCP/IP connection, it consists of two pairs: source host and port, and target host and port. If it's a Linux socket, then it is an entry in that particular machine's directory tree.
A database connection is usually built on one of those constructs, so it, too, is particular to a machine.
Therefore, it doesn't make sense to pass a Connection object to the user who calls your method from some remote machine. And since it doesn't make sense, the JAX-RPC standard does not include a serialization for Connection, and that's why it fails.
Your problem is that you have designed your method such that it accepts a connection as a parameter, and uses that connection to access the database. This works OK locally, but is not a good design for a remote service.
Instead, your method should acquire the connection internally. The remote user should access just the countRows method, with the name of the table, and countRows should call getConnection, use the connection, and the close it.
You shouldn't have a main method in a web service. And the getConnection method should be changed from public to private, so that countRows can access it. When it is private, I believe the web service compiler will not complain about it because it doesn't have to create a serialization for it.
Hi Below is the code I wrote for connecting to Oracle DB using JDBC connection and return some values. But this code establish the connection and returns the result if I am opening the oracle toad in my machine.
But when the oracle toad is closed and try to run this code, it will not connect.
Please let me knwo how to connect to oracle DB with out opening the oracle toad manually.
package library;
import java.io.IOException;
import java.sql.*;
public class DBAutomationConnection {
public static void main(String args[]) throws ClassNotFoundException, IOException, SQLException {
DBAutomationConnection dbconn = new DBAutomationConnection();
//Connection conn = dbconn.DBConnection1();
dbconn.DBConnection1("select * from employee where empid='test123'","ROLE_NAME");
}
public void DBConnection1(String query, String colName)throws IOException, ClassNotFoundException{
Connection connection = null;
Statement stmt = null;
try {
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
connection = DriverManager.getConnection("jdbc:oracle:thin:#//testhostname:1528/ServiceName", "XXAAA_U", "Jw9S");
System.out.println("Connection successful: " +connection);
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
//String UserID = rs.getString("USER_ID");
String UserID = rs.getString(colName);
System.out.println(UserID);
}
} catch (SQLException e ) {
System.out.println("Could not execute query.");
//JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
} catch (SQLException e) {
System.out.println("Could not connect to the database");
}
}
You should initialize Oracle TNS-Listener Service from your OS settings>services. You may need to check your tns configuration.
you need to install ORACLE client in your system to connect oracle remotely.
http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
Do you have Oracle Thin driver installed in your system? This link can guide you.
I have a few DB's in mysql and all of them contain some tables with a few columns. I got the code below from a stack overflow answer.
The answer is at:
How can I detect a SQL table's existence in Java?
The code gives the output-
Driver Loaded.
Got Connection.
Code-
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
System.out.println(rs.getString(3));
} }
static Connection conn;
static Statement st;
static {
try {
// Step 1: Load the JDBC driver.
System.out.println("Driver Loaded.");
// Step 2: Establish the connection to the database.
String url = "jdbc:mysql://localhost:3306/";
conn = DriverManager.getConnection(url, "cowboy", "123456");
System.out.println("Got Connection.");
st = conn.createStatement();
} catch (Exception e) {
System.err.println("Got an exception! ");
e.printStackTrace();
System.exit(0);
}
}
}
In your Code you only
System.out.println("Driver Loaded.");
That's not enough. You have to load the driver first!
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded.");
I'm surprised that this works
conn = DriverManager.getConnection(url, "cowboy", "123456");
and that you come to this line of code.
System.out.println("Got Connection.");
with the following code, it will go, but you will not get a list of tables
static {
try {
// Step 1: Load the JDBC driver.
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded.");
// Step 2: Establish the connection to the database.
String url = "jdbc:mysql://localhost";
conn = DriverManager.getConnection(url,"user","passw");
System.out.println("Got Connection.");
....
}
}
set the database name correctly
static {
try {
// Step 1: Load the JDBC driver.
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded.");
// Step 2: Establish the connection to the database.
String url = "jdbc:mysql://localhost/myDataBase";
conn = DriverManager.getConnection(url,"user","passw");
System.out.println("Got Connection.");
....
}
}
and you can see a list of your myDataBase tables.
This code is used to display the tables of a specific database, not all tables of all DB. You don't specify any database in your url String so there is nothing to display.
If you look carefully at the link used to answer the linked question, you can see String url = "jdbc:hsqldb:data/tutorial"; So you have to be connected to a database first.
PS : You may have to load the driver if you use driver prior to jdbc4, use : Class.forName("com.mysql.jdbc.Driver"); and be sure the driver is available in the classpath.
I am creating a desktop application, in which I have to log in into SQL Server 2005 on the remote machine and have to create a database, User etc. By using jTDS I am able to create a connection to the database as well as able to execute "SELECT" commnads but not able to execute database commands like- create database, create user etc.
Here is my test code:
public class Test {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "net.sourceforge.jtds.jdbc.Driver";
static final String DB_URL = "jdbc:jtds:sqlserver://10.96.11.31:1433;useNTLMv2=true;domain=myDomain";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL);
//STEP 4: Execute a query
System.out.println("Creating database...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
}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 JDBCExample
If you need to create a DB via JDBC then the you'll need a user with permissions to connect to the master database on that server. Create a java.sql.Connection object to the master database then simply create the Statement and execute the SQL:
"CREATE DATABASE MyDB"
I'm a little confused by the question, so I apologize if I misinterpreted it.