I'm trying to connect to my remote database on my VPS using a desktop application built with JAVA.
I have granted access to my ip address by adding this line in the VPS:
After that I have created a JAVA class to test the conenction:
package smt.agm.launcher;
import java.sql.*;
public class Test {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://my_vps:port/my_database";
// Database credentials
static final String USER = "user";
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 * FROM table";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String col1= rs.getString("column1");
String col2= rs.getString("column2");
//Display values
System.out.print("column1: " + col1 + ", column2: "+col2);
}
//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
}
But I have faced this exception:
PacketTooBigException: Packet for query is too large (5 526 600 > 65 535). You can change this value on the server by setting the 'max_allowed_packet' variable.
So I did some research and I have found a way to increase the variable max_allowed_packet using ssh:
vi /etc/my.cnf
and I have increased the value of max_allowed_packet to 500M.
Unfortunately this didn't help and I've got the same exception with the same values:
PacketTooBigException: Packet for query is too large (5 526 600 > 65 535). You can change this value on the server by setting the 'max_allowed_packet' variable.
What am I missing here ?
Related
I am trying to connect to a local MariaDB Database via eclipse and tomcat. When I run the Program i get this message:
java.sql.SQLNonTransientConnectionException: Could not connect to localhost:8080 : unexpected end of stream, read 0 bytes from 4 (socket was closed by server)
at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:240)
at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.getException(ExceptionMapper.java:171)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1132)
at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:561)
at org.mariadb.jdbc.MariaDbConnection.newConnection(MariaDbConnection.java:175)
at org.mariadb.jdbc.Driver.connect(Driver.java:92)
This is the code i am executing:
public void verbinde() {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName("org.mariadb.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(
"jdbc:mariadb://localhost:8080/test?user=root&password=root");
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE REGISTRATION "
+ "(id INTEGER not NULL, "
+ " first VARCHAR(255), "
+ " last VARCHAR(255), "
+ " age INTEGER, "
+ " PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} 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) {
conn.close();
}
} catch (SQLException se) {
}// do nothing
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
//end JDBCExample
the default port of MariaDB is 3306 not 8080
jdbc:mariadb://localhost:3306/test?user=root&password=root
8080 is the port where your tomcat is running
BTW: use try-with-resources instead of the try-catch-finally block
From the CentOS 7 terminal, I can run the java program below by typing javac /path/to/TestJDBC.java. But the problem is that the SYSO commands in the program have no place to go when called from the terminal. How can I change the Java code below so that the SYSO commands get printed to the terminal instead? I know that I could use a FileOutputStream() and then nano the created file name, but I would like to avoid creating a bunch of unnecessary test files.
package somepackage;
//STEP 1. Import required packages
import java.sql.*;
public class TestJDBC {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/somedb?autoReconnect=true";
// Database credentials
static final String USER = "usrname";
static final String PASS = "pword";
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, name FROM peeps";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
//Display values
System.out.print("ID: " + id);
System.out.println(", name: " + name);
}
//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
EDIT
I tried #Immibis's method, and the program starts to run by throws a java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error at the line of code that says Class.forName("com.mysql.jdbc.Driver");. I cannot really evaluate the ability of the program to print to the terminal until errors like this are resolved. How can I resolve this and similar errors in the simple code above?
javac is the compiler. You are compiling your program, but not running it.
Since your package is somepackage, you should have a folder somepackage containing TestJDBC.java. cd to that folder, then run:
javac somepackage/TestJDBC.java
java somepackage.TestJDBC
(It is usually a good idea to make your source folders follow your package structure)
When I try to run the simple Java program below from the CentOS 7 terminal, I get a java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error at the line of code that says Class.forName("com.mysql.jdbc.Driver");. How can I resolve this and similar errors in the code below so that the simple program below will run without errors?
Here is what I have so far:
I navigate to /path/to/ and then type:
javac somepackage/TestJDBC.java
java somepackage.TestJDBC
This results in the error described above. The full code of this simple program is:
package somepackage;
//STEP 1. Import required packages
import java.sql.*;
public class TestJDBC {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/somedb?autoReconnect=true";
// Database credentials
static final String USER = "usrname";
static final String PASS = "pword";
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, name FROM peeps";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
//Display values
System.out.print("ID: " + id);
System.out.println(", name: " + name);
}
//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
You need the library - cannot simplify that away. Previously I'm guessing you used a web app server like JBoss that provided the library for you. Now you're outside the container.
First download the Connector/J jar (contains the JDBC driver class com.mysql.jdbc.Driver) from http://dev.mysql.com/downloads/connector/j/5.0.html.
Then with the jar file in the current working directory, invoke your program something like this:
java -cp mysql-connector-java-5.n.nn.bin.jar:. somepackage.TestJDBC
Also see this SO post: Including jars in classpath on commandline (javac or apt)
HTH
Locate (or upload) the mysql driver jar to the server, then run your code with
java -classpath /path/to/mysql-connector-java-5.0.8-bin.jar:. somepackage.TestJDBC
Adjust the version to whatever you're using.
Does anyone have any ideas of how to connect Access 2010 to java jdbc. I use this method, but when I call it, it doesn't work:
public void loadDb(){
try{
Class.forName("sun.jdbc.JdbcOdbcDriver");
File f = new File(System.getProperty("user.dir"))
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Acess Driver (*.mdb, *.accdb)}; DBQ="+ f.getPath() + "//db//JavaAccess.accd","","");
st = con. createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
}catch(ClassNotFoundException e){e.printStackTrace();
}catch(SQLException e){e.printStackTrace();}
}
//con and st are already defined
According to msdn it should be sun.jdbc.odbc.JdbcOdbcDriver. So replace this line of code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Spelling error? Perhaps this line:
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Acess Driver (*.mdb, *.accdb)}; DBQ="+ f.getPath() + "//db//JavaAccess.accd","","");
should be
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ="+ f.getPath() + "//db//JavaAccess.accd","","");
Access has 2 C's
Create connection
public static Connection getConnection() {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:anime"; //anime is the database
String username = "ipieluser"; //leave blank if none
String password = "ipielpassword"; //leave blank if none
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
How to call:
public static void main(String args[]) {
try {
Connection conn = getConnection();
Statement st = conn.createStatement();
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM localTable");
//get and displays the number of columns
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
st.close();
conn.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
Use UCanAccess JDBC Driver :
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); // can be omitted in most cases
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<mdb or accdb file path>",user, password);
e.g.:
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://c:/pippo.mdb");
So for your example it will be
con = DriverManager.getConnection("jdbc:ucanaccess://"+f.getPath()+"/db/JavaAccess.accd")
Rishab's reply helped me to connect to my access database.
I did following correction in the code:
Instead of
String url = "jdbc:odbc:anime"; //anime is the database
I did
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=" + "d://institute//institutedata.accdb";
I explicitly defined driver and full database name with path and extension.
As today only we face the same problem and found that to check the version of java if your
version of java if the version of the java is above 7 then the sun.jdbc.odbc.JdbcOdbcDriver will not be supported so just check the version of the java.
I'm getting the cannot find symbol error from my code. Does anyone know what can cause this problem?
The code is:
// Register JDBC driver
Class.forName("net.sourceforge.jtds.jdbc.Driver");
and the error output is:
blah.java:314: cannot find symbol
symbol : method forName(java.lang.String)
location: class java.lang.Class
Class.forName("net.sourceforge.jtds.jdbc.Driver");
^
1 error
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.sql.jdbc.Driver";
static final String DB_URL = (":jdbc:jtds:sqlserver://localhost:1433/tempdb" );
// 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("net.sourceforge.jtds.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 database...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE ";
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
The main way in which Class.forName() can fail is not having the JDBC drivers available on the class path but that would be a run-time error, not a compile-time error as you seem to be getting here.
Using my powers of psychic debugging, I think you may be using GWT. I don't believe it allows that on the client side (where it's converted to JavaScript). All JDBC stuff has to stay on the server side. Google themselves publish the JRE emulation reference so you can see what is allowed.
The supported methods of Class are limited to:
desiredAssertionStatus()
getEnumConstants()
getName()
getSuperclass()
isArray()
isEnum()
isInterface()
isPrimitive()
toString()
If I am right about the fact you're using GWT, it's probably best to use GWT-RPC to talk between the client and server, and have the server itself issue JDBC calls.
If you want further information on GWT-RPC, see here. There's a thread in the GWT news group which you can read for further information.
There can be a scenario where you have a class named "Class.java" in the same package. In that case it ignores the "Class.java" in java.lang package. Since you didn't implement a method called "forName()" in your "Class.java", it throws this error.
It occurred to me when I got a similar compile-time error.