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)
Related
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 ?
I am trying to establish a connection but for some reason I am having issues doing so.
I think it may be a syntax error - but I am not completely sure. I have commented out numerous syntax approaches I have tried. I used MySQL documentation for help, even when following their syntax i get problems.
When I run the code without the Connection the program jumps into the try. But as soon as I add the Connection code it jumps to the catch section of the code - therefore there must be an issue with the syntax.
Can anyone spot where I have gone wrong? Thank You in advance.
public void selectData()
{
try
{
Connection con = null;
//Accessing driver from the JAR file
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Class.forName("com.mysql.jdbc");
//String a = "jdbc:mysql://localhost:3306/c3361434?profileSQL=true";
///String a = "jdbc:mysql://address=(protocol=tcp)(host=localhost)(port=3306)(user=root)(password=root)/c3361434";
//Connection con = DriverManager.getConnection("jdbc:mysql://address=(protocol=tcp)(host=localhost)(port=3306)(user=root)/c3361434");
//Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/c3361434", "root", "root");
//con = DriverManager.getConnection("jdbc:mysql://localhost:3306/c3361434?" + "user=root&password=root");
Output3.setText("Connection has been established");
/*
PreparedStatement statement = con.prepareStatement("SELECT * FROM RSA-data");
ResultSet result = statement.executeQuery();
while(result.next())
{
Output2.setText(result.getString(1));
Output3.setText("in the while loop");
}
*/
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
Output4.setText("db fail");
}
}
try it:
Check if you mysql is running, in command line type:
mysqld --install
In java source:
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDB?dontTrackOpenResources=true");
the command mysqld not reconized because you need to enter at path specific.
For example:
MS - DOS:
cd C:/MySQL/bin
C:/MySQL/bin>mysqld --install
Into folder bin there is the mysqld.exe
Do you got it ?
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.
I have 1 basic program and 1 app, My basic program with this works ( DB_URL, USER, PASS, JDBC_DRIVER all correct and functional) and I am able to get information from my MySQL DB. The code consist of this:
try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
// STEP 3: Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT distinct tags FROM items";
ResultSet rs = stmt.executeQuery(sql);
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
String itemRoles = rs.getString("tags");
//Add it to the ArrayList.
itemRolesList.add(itemRoles);
// Display values
System.out.print("TAGS: " + itemRoles + "\n");
}
// 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
But when I try to apply this same code to my app (inside a Fragment in my OnCreateView()) I get this:
"java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"
and it is at this line of code:
Class.forName(JDBC_DRIVER);
I added the "mysql-connector-java-5.1.23-bin.jar" and it is in my Reference Library in both my program and app. Does anyone know why inside my app it gives me this error?
Make sure that you have driver jar in your classpath.
Please verify that you have jar file inside lib folder is not the empty jar file.sometime during wrong confuguration it shows a empty jar file.
please go to project properties-->buildpath-->libraries
Check out the jar file you have added is not blank.
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.