I'm getting java.lang.ExceptionInInitializerError when I connect to JDBC - java

I'm running a server using Tomcat 7.0 in Eclipse.
I have a html file to link to a Servlet file, which has a form to input the value.
When I input any value in the html file, it forwards to the servlet file, and the servlet file has some codes to connect JDBC.
The code is quite simple.
data = request.getPrameter("name");
Connection conn = DriverManager.getConnection(url, username, password);
I've imported everything to be used.
Also, in the tomcat server, I added permission in catalina.policy
grant{
permission java.net.SocketPermission "*:1-65535", "connect,resolve";
};
I'm not sure why I'm getting this error.
I'm happy to give you more information if needed!
Please help me :)

I had detailMessage saying access denied ("java.util.PropertyPermission" "file.encoding" "read").
So I added permission java.util.PropertyPermission "file.encoding", "read"; and all fixed
It'd be great if this helps anyone who's in trouble

I have met this problem when I used jdbc connect to teradata database,
that because it need two jar files but I just gave one jar file:
jdbc_driver_loc = '/opt/spark-2.3.1-bin-without-hadoop/jars/terajdbc4-16.20.00.06.jar'
jpype._jexception.ExceptionInInitializerErrorPyRaisable: java.lang.ExceptionInInitializerError
when I added the other one, it works:
jdbc_driver_loc = '/opt/spark-2.3.1-bin-without-hadoop/jars/terajdbc4-16.20.00.06.jar,/opt/spark-2.3.1-bin-without-hadoop/jars/tdgssconfig-16.20.00.06.jar'
Whole sample like that:
[root#myhost transfer]# cat test_conn.py
import jaydebeapi
from contextlib import closing
jclassname='com.teradata.jdbc.TeraDriver'
jdbc_driver_loc = '/opt/spark-2.3.1/jars/terajdbc4-16.20.00.06.jar,/opt/spark-2.3.1/jars/tdgssconfig-16.20.00.06.jar'
jdbc_driver_name = 'com.teradata.jdbc.TeraDriver'
host='my_teradata.address'
url='jdbc:teradata://' + host + '/TMODE=TERA'
login="teradata_user_name"
psw="teradata_passwd"
sql = "SELECT COUNT(*) FROM A_TERADATA_TABLE_NAME where month_key='202009'"
conn = jaydebeapi.connect(jclassname=jdbc_driver_name,
url=url,
driver_args=[login, psw],
jars=jdbc_driver_loc.split(","))
with closing(conn) as conn:
with closing(conn.cursor()) as cur:
cur.execute(sql)
print(cur.fetchall())
[root#myhost transfer]# python test_conn.py
[(7734133,)]
[root#myhost transfer]#

Related

How do I avoid an 'unknown database' error when using a custom database directory?

I'm working on a project and I have put my database folder in project folder. How can I make a database connection to any directory rather than just default MySQL dir in Java?
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
String UserName = "root";
String Password = "admin";
Connection con = null;
try {
con = DriverManager.getConnection(MySQLURL,UserName,Password);
if (con != null) {
System.out.println("Database connection is successful !!!!");
}
} catch (Exception e) {
e.printStackTrace();
}
When doing this, I get this error:
java.sql.SQLSyntaxErrorException: Unknown database 'c:\program files\snakegame'
Your connection URL is wrong
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
I am not sure why your MySQLURL contains C:\Program Files\SnakeGame
The connection URL for the mysql database is
jdbc:mysql://localhost:3306/[DatabaseName]
Where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running (we may also use the server's IP address here), 3306 is the port number, and [DatabaseName] is the name of the database created on the MySQL server.
Replace the [DatabaseName] name accordingly after creating the database in MySQL server
Combining localhost:3306/ with C:\\Program Files\\SnakeGame makes little sense for any database - either you're trying to connect to a file-based database (in which case the localhost... part makes no sense) or you're working with a server-based one (in which case the C:\... part makes no sense.
Also, this connection string would make little sense for a file-based database either because you didn't specify a specific file, just a path.
Incidentally, MySQL is server-based, not file-based. It's expecting a database name after the localhost:3306/ part, not a path (hence the error). The physical location of the actual database program is an installation/configuration issue - it has nothing to do with how you actually connect to the database server once it's already running.
Think about it this way: when you call an external database, web service, or web site, do you need to know which physical folder it's deployed to? Obviously not. The physical folders involved are completely irrelevant when calling MySQL or another database like this.
One of the comments pointed this out, but did you intend to use SQlite or some other file-based database here instead?

Why is this mySQL database not connecting to Netbeans?

The mysql database will not connect to the netbeans code. I am using a Mac Device and have installed mySQL on my device (it is running fine on localhost:8080). However, the connection through Java is not working. I believe there may be an error in the following line "conn = Driver Manager..." since it is not executing. I am unsure of how to change the password / what the password is.
Restarting Xampp
Screenshot of connection code
Expected result: user input is sent to mySQL database
Actual result (error): seen in this screenshot
This is the general database connectivity code .
try
{
Class.forName("java.sql.DriverManager");
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","MysqlUsername","MysqlPassword");
Statement stmt = (Statement) con.createStatement();
String query = "YourMysqlQuery";
stmt.executeUpdate(query);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
// You also have to add 'jdbc driver' in lib folder of your project.
If want us to solve the problem in your code then please provide the actual code you have done , Not the image .

Connection in Java to a Database

I'm working on OS X, Eclipse, Java 8 and MySQLWorkBench.
I realize with the last a database (can I say schema?), named "mydb" located at localhost:3306 (I don't know exactly what it means)...
Now I would like to connect via a java program to this db.
I'm trying with
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb");
It follows the error message
Exception in thread "main" java.sql.SQLException:
No suitable driver found for jdbc:mysql://localhost:3306/mydb
Can someone tell me what's wrong?
You need to download the jdbc driver and add it to your project
Download the driver from here
Example on how to add the driver in eclipse
Also you need to include the username and password in the connection statement and make sure you call the Class for name to get the driver loaded
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection(DB_URL,USER,PASS);
You haven't added required library to connect java application with MySql database.you can download it form here.After once you get downloaded , just extract zip wherever you want.And add it into your project library folder.
Right click on project goto property -> java build path -> add external jar .
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","userName","userPass");
where userName is your database username and userPass is your password corresponding to that user.
After download and adding the Connector/J to your build path like #Jacques said.
Try this code:
try {
// Load the JDBC driver
#SuppressWarnings("rawtypes")
Class driver_class = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) driver_class.newInstance();
DriverManager.registerDriver(driver);
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", getDbUser(), getDbPassword());
return conn;
} catch (Exception e) {
// TODO: handle exception
}
Where getDbUser() is your database username and getDbPassword() is your database password.

How to connect to mysql using eclipse running apache

I am creating a dynamic web project in eclipse. I have my local apache server running and configured with appropriate resource, mysql running and configured with the appropriate port.
I downloaded the appropriate driver, included it in the lib directory - I even tried adding it as an external JAR file to no avail. On the dynamic web page the result is "error connecting to database".
I created a JSP with the following code:
<%# page import="java.sql.*"%><%# page import="java.io.*"%><%# page import="com.mysql.*"%><?xml version="1.0"?>
<tours>
<%
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jbdc:mysql://localhost:3306/tours", "root", "root");
out.println("connected to database!");
}
catch(SQLException e) {
out.print("error connecting to database");
}
%>
</tours>
Please advise...
Thanks in advance.
Put print after Class.forName() check, if that statement is not printing then problem is driver if that line is printing then problem is mysql database name problem or credential problem
If problem in drive then download from here :
http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm
Problem is u put jbdc instead of jdbc
Code like this
<%
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
out.println("Driver is available !");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tours",
"root", "root");
out.println("connected to database!");
}
catch(SQLException e) {
out.print("error connecting to database");
}
%>
There are couple of things to take care of here.
1. Make sure that mysql is listening on port 3306.
2. Cross check the database name.
Lastly get the driver jar file in deployment assembly.
If the problem still persists, please print the stacktrace and post it here.
Please check weather your database is started or not i know it should be in comment but i cannot keep it in comment because i don't have sufficient reputations. please try it if it helps you it is fine.
How to start database is shown below:
Click Windows button+r then enter Services.msc in search bar then select Mysql and click start option
Printing the stack trace might help it could be because of authorization issue. If the error is related to authorization issue, you may have to change the server configurations.

Java RMI AccessControlException: access denied

Hey I'm getting a AccessControlException: access denied when attempting to start up a RMI app I'm writing, I can't work out why I get this exception if I open it on the default port 1099, or on another dynamic port, my policy file currently grants everything (will change when app is finished).
I am stuck as to where it is going wrong, any help would be of great use
My code
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws RemoteException, AlreadyBoundException, MalformedURLException {
if (System.getSecurityManager() == null)
{
System.setSecurityManager ( new RMISecurityManager() );
}
CreditCardServer ccs = new CreditCardServer();
int port = 1099;
try {
port = Integer.valueOf(args[0]);
}
catch (Exception e)
{
System.out.println("Invlaid Port");
}
if (((port <= 65535) && (port >= 49152)) || port ==1099)
{
System.out.println("Valid Port");
}
else
{
port = 1099;
System.out.println("Port not in Dynamic Range 49152<-->65535");
}
System.out.println(port);
LocateRegistry.createRegistry(port);
LocateRegistry.getRegistry().bind("CreditCardServer", ccs);
while (true)
{
//hum?
}
}
}
The Stack Trace
vega3 [ia32.linux] 23% java -Djava.security.policy=wideopen.policy -jar "BookStore-CreditCardServer.jar 65000"
Valid Port
65000
Exception in thread "main" java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:1099 connect,resolve)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:342)
at java.security.AccessController.checkPermission(AccessController.java:553)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.lang.SecurityManager.checkConnect(SecurityManager.java:1051)
at java.net.Socket.connect(Socket.java:536)
at java.net.Socket.connect(Socket.java:492)
at java.net.Socket.<init>(Socket.java:389)
at java.net.Socket.<init>(Socket.java:203)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:146)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:340)
at sun.rmi.registry.RegistryImpl_Stub.bind(Unknown Source)
at bookstorecreditcardserver.Main.main(Main.java:56)
My Policy File
grant {
// Allow everything for now
permission java.security.AllPermission;
};
I've been stuck on this all day (after figuring out I had to start the rmiregistry from the commandline), trying to make this work locally with Eclipse, and finally solved it. A few pointers to save others this cruel fate:
1 - assign the policy file correctly, either with a commandline flag:
java -Djava.security.policy=/home/.../<filename>.policy ...
or by putting this directly in your code:
System.setProperty("java.security.policy","file:///home/.../<filename>.policy");
You can also put it in the same folder as your project root), to reduce the URI to
file:./<filename>.policy
(use a relative instead of absolute URI - I actually didn't understand this until today).
2 - make sure the format of the policy file is correct, e.g.:
grant codeBase "file:<path>/bin/-" {
permission java.security.AllPermission;
};
This should refer to the folder where your binary is located! A thorough explanation of the format of the policy file is here.
That's about it, I'd also recommend this tutorial, I found it very helpful to get on the right track.
Basically, I'm stupid, i assumed that because Java was not complaining it was finding the .policy file AOK, turns out it was not moving a new copy of the.policy file into the working directory solves all :-D
I found most of the answers on this topic vague and unhelpful, and spent several hours debugging this. More than likely, your error is because the policy file is either incorrectly formatted or you're not correctly setting it as a command line argument.
If you're getting a java.security.AccessControlException: access denied ("java.net.SocketPermission" "127.0.0.1:1099" "connect,resolve")
Create a security policy file with all permissions, just to test it out
grant codeBase "file:/-" {
permission java.security.AllPermission;
};
Use this security file for both the client and the server, just to get it running.
Make sure you don't have any typos. I spent hours trying to figure out why it wasn't working, and i had typed -Djava.rmi.security.policy instead of -Djava.security.policy=...
For those of us that just want to get the RMI tutorial from Oracle up and running, this security policy will be more than enough for that example.

Categories