I have a Unix Instance ready on Amazon EC2 .I have installed mysql in it which is runnig on 3306 port. ( Note: It is not rds database from AWS)
I have created EmpDB databse in Mysql and have created Employee table. And I have written a java program to insert a row in Table.
Below is the code:
import java.sql.*;
import java.util.Calendar;
public class Test{
public static void main(String[] args) {
try{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/TaskDB";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "root");
String query = " insert into employee (id,name,dept,salary)"
+ " values (?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, 600);
preparedStmt.setString (2, "Rubble");
preparedStmt.setString(3, "startDate");
preparedStmt.setInt(4, 5000);
preparedStmt.execute();
conn.close();
} catch (Exception e){
System.err.println("Got an exception!");
e.printStackTrace();
}
}
When I am executing it via "java Test", getting below error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:359)
at java.net.URLClassLoader$1.run(URLClassLoader.java:348)
at java.security.AccessController.doPrivileged(Native Method)
at java.net
How I can install mysql connector on my Unix Instance?
Just copy the MySql-Connector.jar into Tomcat's lib folder, and then remove the jar from the webapp's lib folder, and then, re run the project.
import com.mysql.jdbc.Driver;
Put the driver in the same folder as my Test.java file, and compile it, resulting in Test.class.
So in this folder have
Test.class
mysql-connector-java-5.1.14-bin.jar
and I write this:
java -cp .;mysql-connector-java-5.1.14-bin.jar Test
This way if you not use any IDE just cmd in windows or shell in linux.
Related
I'm trying to connect with SQL Server local database, I connected with it successfully from IntelliJ level, and there was information that I need to install jTDS driver to use it. I downloaded latest version of it and added as a library from my lib dir in project, despite this java says that it couldn't find the class, maybe I installed it wrong? Here is my code
import java.sql.*;
public class Main {
public static void main(String [] args) throws ClassNotFoundException, SQLException {
Class.forName("net.sourceforge.jtds");
Connection connection = DriverManager.getConnection("jdbc:jtds:sqlserver://./TPO");
Statement statement = connection.createStatement();
String sqlString = "SELECT * FROM Books";
ResultSet resultSet = statement.executeQuery(sqlString);
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}
}
I'm trying to connect the database with Netbeans with the help of oracle 10g. I have downloaded odjbc7.jar file and added it in the ORACLE THIN driver in db services. Still, I'm getting this class not found exception. (I am using Apache netbeans).
enter code here
import java.sql.*;
public class jdbclass {
public static void main(String args[]) throws ClassNotFoundException, SQLException
{
String url="jdbc:oracle:thin:#localhost:1521:orcl";
String uname="sh";
String passwd="ara";
String query="select pizza_type from pizza";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(url,uname, passed);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query);
String name=rs.getString("pizza_type");
rs.next();
System.out.print(name);
st.close();
con.close();
}
}
You should use ojdbc14.jar as mentioned at https://docs.oracle.com/cd/E19830-01/819-4721/beanh/index.html
Make sure you have added the jar in the classpath as mentioned at How do I set the classpath in NetBeans?
This question already has an answer here:
Exception in thread "main" java.sql.SQLException: Access denied for user ''#'localhost' (using password: NO)
(1 answer)
Closed 2 years ago.
I'm making a java project with SceneBuilder and Eclipse; i need to connect to a local database created using MySQL, but after running my Java code in eclipse i get the following error:
Exception in thread "main" java.sql.SQLException: Access denied for user ''#'localhost' (using password: NO)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.mysql.cj.jdbc.admin.TimezoneDump.main(TimezoneDump.java:70)
Instead of 'root'#'localhost' (using password: NO) that is a login credentials error, now i have ''#'localhost' (using password: NO).
Using MySQL workbench and command prompt, i can correctly access using "root"/"root", and launch queries on my db. Running the same Eclipseproject on another laptop or my home pc, i can run it without errors. So the problem is not in the code but in some setting of my current laptop.
I already tried to:
Uninstall and reinstall Eclipse.
Uninstall and reinstall mySQL products: Workbench, Server, J Connector.
Switch Eclipse workspace.
Open the 3306 port from windows firewall.
That's the part of the code where i try to connect to my db.
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class UserDAO {
private static String USER = "root";
private static String PASS = "root";
private static String DB_URL = "jdbc:mysql://127.0.0.1:3306/beecological?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
private static String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
public static boolean checkUsername(String username) {
Statement stmt = null;
Connection conn = null;
int res = 1;
try {
Class.forName(DRIVER_CLASS_NAME);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
res = Queries.verifyUsernameAvailable(stmt, username);
stmt.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
if(res == 1) {
return false;
}
return true;
}
public static void saveUser(User instance) {
Statement stmt = null;
Connection conn = null;
try {
Class.forName(DRIVER_CLASS_NAME);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Queries.insertUser(stmt, instance);
stmt.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
public static boolean verifyLogin(User instance) {
Statement stmt = null;
Connection conn = null;
int res = 0;
try {
//caricamento driver mysql
Class.forName(DRIVER_CLASS_NAME);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
res = Queries.verifyUserRegistered(stmt, instance);
stmt.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
if (res == 0) {
return false; //utente immesso non esiste
}
return true;
}
}
Solution
The problem was not about MySQL login credentials, but on Eclipse configuration.
In my folder project the .classpath and the .project files were corrupted. Infact going to myproject>right click>Run As..>Run Configurations the main class was setted as com.mysql.cj.jdbc.admin.TimezoneDump.main instead of my mainApp class. Trying to change there the main class file not worked, because for Eclipse the mainApp doesn't exist.
So this is what i've done to solve the error:
Delete the project from Eclipse (not on the disk)
Close Eclipse
Go to Project folder and delete .classpath and .project files
Open eclipse, go to File > Open projects from File System and choose the project directory
Right click on the project > Run As > Run Configurations and set the right Main class
I am trying to connect to mysql database and that is not done still because of the error,My code is as follows:
public static void main(String[] args) {
try{
String url = "jdbc.mysql://localhost:3306/db";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url,"root","root");
Statement stmt = conn.createStatement();
String query = "insert into student values(1,abs)";
stmt.executeQuery(query);
System.out.println("Success...");
conn.close();
}catch(Exception e){
e.printStackTrace();
}
And the error is as follows:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Java_Database.main(Java_Database.java:11)
So anyone know well please help me.
1: download that msi you referred to # http://dev.mysql.com/downloads/connector/j/
2: run it. after it runs the install app vanishes, not exactly a roadmap for success for an install routine
from the root of c:\ I issue: dir mysql-connector-java-5.1.36-bin.jar /s
I let it run the whole way thru to confirm I didn't already have it installed elsewhere
C:\>dir mysql-connector-java-5.1.36-bin.jar /s
Directory of C:\Program Files (x86)\MySQL\MySQL Connector J
06/19/2015 09:26 PM 972,009 mysql-connector-java-5.1.36-bin.jar
1 File(s) 972,009 bytes
Total Files Listed:
1 File(s) 972,009 bytes
Seems consistent with my 5.1.35 filesize I was using before stumbling into your question
Btw, the above MySql Connect J folder date was just created so I am sure that was from the install
I copy (not moving it) it to my c:\javadeps folder.
I have a database called so_gibberish, and a table called thingws with 3 rows in it
source code (myTest.java):
I poached this stub off the internet as I am mostly a scala/jvm programmer. So please forgive. But it works.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class myTest {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/so_gibberish"; // **** MODIFY db name # end
String user = "stan"; // **** MODIFY
String password = "stan_password"; // **** MODIFY
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
System.out.println("------------------------------");
rs = st.executeQuery("select version()");
if (rs.next()) {
System.out.println(rs.getString(1));
System.out.println("------------------------------");
}
rs = st.executeQuery("select id,myCode from thingws");
while (rs.next()) {
System.out.println(rs.getInt(1)+": "+rs.getString(2));
}
System.out.println("------------------------------");
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(myTest.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(myTest.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
I will save it in C:\dev\java8\quick_java_mysql_test
compile and run (when you run it, it does a query for the mysql version, then a query on that table getting 3 rows)
c:\dev\java8\quick_java_mysql_test>javac myTest.java
c:\dev\java8\quick_java_mysql_test>java -cp .;c:\javadeps\mysql-connector-java-5.1.36-bin.jar myTest
output is:
------------------------------
5.6.24-log
------------------------------
1: C938CA
2: XYZ123
3: XYZPDQ
------------------------------
It is common to have a dependencies folder for jars at the project-level, such as a dep directory under the project folder.
Though I have that same jar file in it, it is not referenced, as seen in the -cp directive in step 7
that picks the jar up in c:\javadeps
plan your strategy according, and good luck
The mysql driver jar is not in the classpath.
Download it and copy it to a location visible from the classpath.
Here the link to the official driver.
You are using JDBC driver/connector for MySQL in your code.
You may download from below mentioned link.
https://www.mysql.com/products/connector/
I am getting ClassNotFoundException in this code when I run it on a server But as a stand alone java file it runs fine.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import UserJavaBean.UserJavaBean;
public class UserDataBase {
public int insert()
{
int flag =0;
try
{
UserJavaBean user= new UserJavaBean();
//Statement stmt= null;
PreparedStatement ps= null;
//ResultSet rs= null;
Connection conn;
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Class Loaded");
conn= DriverManager.getConnection("jdbc:oracle:thin:#localhost:****:orcl","hr","hr");
System.out.println("Connection Established");
// stmt= conn.createStatement();
int emp_id= user.getId();
String emp_name=user.getName();
String emp_des=user.getDesignation();
ps = conn.prepareStatement("insert into nanda values(?,?,?)" );
ps.setString(1,emp_name);
ps.setInt(2,emp_id);
ps.setString(3,emp_des);
ps.executeUpdate();
flag=1;
}
catch(Exception e)
{
e.printStackTrace();
flag=0;
}
System.out.println("flagvalue"+flag);
return flag;
}
}
You have not provided exception stacktrace. But I think you should provide the respective jar file of oracle.jdbc.driver.OracleDriver in class path as well as inside lib folder. You might have forget to provide the jar file inside lib folder of the project. As you are not getting any error during stand alone run, you have provide the jar file in class path and it is taking the class path jar file. But when you deploy your web application you have to provide the same jar file inside the lib folder. So that after deployment it will take the jar file from lib folder.
In a nutshell, After deployment, the class path jar files are not available for web app.
I think this will resolve your problem. Try it and let me know.