i have a database for practice at phpMyAdmin. i use XAMPP. I am in very early stages of learing about the conection with a database. I followa tutorial and i think i am understanding the concept and everything is cool. But i stepped on a problem that despite the fact that there are answers on the internet, i cant solve it. here is my code:
import java.sql.*;
public class DBConnect {
private Connection connection;
private Statement statement;
private ResultSet result;
public DBConnect(){
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:1234/practicedb"); //code stucks here and after some minutes it is throwing an exception
System.out.println("Connected");//this is never executed.
statement = connection.createStatement();
} catch (Exception ex) {
System.out.print("Error in Constractor: "+ex);
}
}
public void getData() {
try {
String query = "select * from cars";
result = statement.executeQuery(query);
while (result.next()) {
String name = result.getString("carName");
String id = result.getString("carID");
String modelNum = result.getString("modelNumber");
System.out.println("Car name: " + name + ", " + "Car ID: " + id + ", " + "Car model number: " + modelNum);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
In the main class i create an instance of the class and then call the getData().
The code stucks in that line:
connection = DriverManager.getConnection("jdbc:mysql://localhost:1234/practicedb");
And it throws that:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.java.lang.NullPointerException
This similar question was answered here: answer
But the suggestions are poor. I have tried flushing dns. I checked the URL and this is the one i connect to the database on phpmyadmin. i changed localhost to my ip adress. but all those just dont work.
I would really appreciate help. Is the first step on managing to receive that knowledge and i actually cant proceed at the moment. Thank you :)
i noticed that if i change the localhost:1234 to a random one like localhost:5432 it is throwing the error immediatelly. But when i have it on 1234(which i the port i have choosen through xampp config) then the programm runs for round about 5 minutes before it got terminated with the exception
Usually MySQL listens on the default port 3306.
If your database is named practicedb then your code should look like this:
private Connection connection;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/practicedb");
System.out.println("Connected");
} catch (Exception ex) {
System.out.print("Error creating connection: "+ex);
}
Related
Heading ##I have problem with my java application with database in mySQL and swing GUI.
When I've used localhost everything worked properly. But now I would like to share project with my friend and we decided to use server hosting.
And here is a problem:
Now application works very slow, after pressing a button I have to wait a few seconds for the program to respond. Also the connection is lost from time to time. I have no idea where can I find reason for the problem... Do somebody now what is the reason of this problem?
private static Connection connection = null;
Boolean error = false;
private static String jdbcURL = "jdbc:mysql://host_name:3306/db_name";
private static String user = "user";
private static String password = "password";
MakeConnection(Connection connection) throws SQLException{
this.connection = connection;
try {
getConnection();
System.out.print("Connected to the data base in MakeConnection");
}
catch(Exception e) {
error = true;
System.out.print("Error in connection in MakeConnection consturctor" + e.getMessage());
}
finally{
if(connection!=null) connection.close();
if(error) System.out.print("Problem with connection");
else System.out.print("Program finished");
}
}
public Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL,user,password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
Also sometimes application shows this error:
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I don't see any problem in your code. The problem is probably with your server hosting. You should check the country of the host provider and measure the time required to send a request to the server. Also you should use logger instead of System.out.println so you can examine required time for actions like db access, application logic and find a bottleneck.
I have a problem when running my code in NetBeans in order to see if mySQL is connected. This is the code:
public static void main(String[] args) {
Connection connect = null;
try{
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}
}
}
when I run it prints out "RIP". When I debugged it line by line, it went from the "connect = DriverManager.getConnection..." to "System.out.println("RIP"), and when I look at the "Exception e" it says "e = (java.sql.SQLNonTransientConnectionException) java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the connection string near '=TRUE'."
Now, why is that?????
I think you need to add
Class.forName("com.mysql.jdbc.Driver"); .
Also, make sure everything in Connection conn = DriverManager.getConnection (String url, String user, String password); are set correctly.
From the url format in your code, it's like you are trying to get direct connect to specific table tUsers in your database. And I dont think that would work. Correct me if I'm wrong whether it's literally your database name or not.
Because the basic url format i know, should be like jdbc:mysql://localhost:3306/yourDBname .
If you already set the url correctly as is written in your post, then the code is
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}}}
Hope that could do the work.
I am following a tutorial on connecting my SQLite database to a Java application.
When I run the program I get the following error in the console of NetBeans:
run:
Error connecting to the databasejava.sql.SQLException: No suitable
driver found for jdbc:C:\Users\lawman\Documents\Java Working
Directory\LoginSql\src\project123.sqlite
BUILD SUCCESSFUL (total time: 0 seconds)
Here is my directory:
I have code to connect to the database in class tobecalledbymain.
I have main in mainclass which creates an instance of tobecalledbymain.
In my library file, I have sqlite-jdbcs.jar imported.
Here is the code for tobecalledinmain:
import java.sql.*;
public class tobecalledinmain {
public tobecalledinmain(){
Connection con = null;
Statement st=null;
ResultSet rs=null;
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:C:\\Users\\lawman\\Documents\\"
+ "Java Working Directory\\LoginSql\\"
+ "src\\project123.sqlite");
st=con.createStatement();
//select all records from the table employee
//table has three firlds: employeeid,name and surname
rs=st.executeQuery("SELECT * FROM Employee;");
while (rs.next())
{
int id = rs.getInt("Employeeid");
String name = rs.getString("Name");
System.out.println("id = " + id);
System.out.println("name= " + name);
System.out.println();
}
rs.close();
st.close();
con.close();
}catch(Exception e)
{
System.out.println("Error connecting to the database" + e);
}
}
}
Here is the mainclass code:
public class mainClass {
public static void main(String[] args){
new tobecalledinmain();
}
}
;;
I am not sure why we need to semi-colons!
Anyway, when the tutorial concludes he gets a result from the console. I get the said error message.
What are the drivers in the error message referring to and how do I get them?
Your jdbc connection string does not specify sqlite. Try this, and use forward slashes.
Connection con = DriverManager.getConnection("jdbc:sqlite:C:/PATH/TO/database.db");
This was the WRONG answer, pls disregard.
You need to add the .jar for the SQLite database driver to your classpath when you run your code. See https://bitbucket.org/xerial/sqlite-jdbc
You can see how to do that in Netbeans here: How to add a JAR in NetBeans
I'm trying to access a MS_Access db using StelsMDB library. The file is on the SD card of the phone. I loaded all libraries, created the connection:
public class DBConnection {
private static final String TAG = DBConnection.class.getSimpleName();
private Connection connection;
public DBConnection() {
try {
Class.forName(jstels.jdbc.mdb.MDBDriver2.class.getName());
connection = DriverManager.getConnection("jdbc:jstels:mdb:sdcard/2012xp.mdb");
} catch (SQLException e) {
Log.e(TAG, "", e);
} catch (ClassNotFoundException e1) {
Log.e(TAG, "", e1);
}
}
public Connection getConnection() {
return this.connection;
}
}
and it seems to work; but when i try to query something i get the following exception:
Failed parsing query
java.lang.IllegalStateException: unknown query object flag 3
Online i can't find any hint. I get this exception with a complex query, so i tryied to write an easier one like
"SELECT * FROM TABLE_NAME"
....but i get the same exception.
I belive you have a mistake in the connection string. You need to creat Connection object with it's atributes.
Try replacing your connection with this:
Connection conn = DriverManager.getConnection("jdbc:jstels:mdb:sdcard/2012xp.mdb");
After a long trying i found out that jStels is not compatible with android...
Hello all I have a basic Storm application set up where it receives a stream of tweets and stores them in a MySQL database. The application works great for the first ~23 hours or so then it starts giving the following error:
SQL Exception
SQL State: 08003
After it does this a few times it dies. I'm using the standard JBDC connector to connect to the database from Java. The code for the functions for storing and setting up the DB connection are as follows:
private String _db="";
private Connection conn = null;
private PreparedStatement pst = null;
public ArchiveBolt(String db){
_db = db;
}
private void setupConnection() {
//Connect to the database
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:8889/twitter_recording", "root", "root");
} catch (Exception e){
e.printStackTrace();
}
}
public void execute(Tuple tuple, BasicOutputCollector collector) {
Status s = (Status) tuple.getValue(0);
//setup the connection on the first run through or if the connection got closed down
try {
setupConnection();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
}
try {
pst = conn.prepareStatement("INSERT INTO " + _db + " (tweet)" +
"VALUES (?);");
pst.setString(1, s.toString());
//execute the SQL
pst.executeUpdate();
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
if(ex.getSQLState().equals("08003")){
setupConnection();
}
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
After it became apparent that it was crashing because of a 08003 error I decided that if it threw that error it should retry the set up of the connection, however that didn't help either. Could anyone point me in the right direction for solving this issue?
After it became apparent that it was crashing because of a 08003 error I decided that if it threw that error it should retry the set up of the connection, however that didn't help either. Could anyone point me in the right direction for solving this issue?
There are basically two problems here that need to be solved:
Why are the connections getting lost in the first place?
Why isn't your attempt to reconnect succeeding?
For the first problem, you should take a look at the MySQL logs to see if there are any indications there. And also, check for SQL exceptions immediately prior to the (repeated) "state 080003" exceptions. The latter are simply telling you that the connection has died previously.
My guess is that the problem is one of the following:
The MySQL server has timed out the connection due to inactivity. You can change the connection timeout in the MySQL configs if this is the problem.
Your application may be slowly leaking JDBC connections.
For the second problem, the general approach is correct, but your code doesn't match the description. In fact, it looks like it is always trying to establish a new database connection each time your execute method is called. This renders the reconnection call in your exception handler pointless. (OTOH, the code show signs that someone has been "beating on it" to try to get it to work ... and that could well be part of the problem.)
I would check that setupConnection is being called when it needs to be, and look for any exception that might be thrown. In addition, you should make sure that you explicitly close() the dead connection object ... and rethink / recode your connection management so that it doesn't leak.
For the record, there is a connection URL parameter called "autoReconnect" that in the distant past used to "deal" with lost connections. Unfortunately, the original implementation was unsafe, so they effectively disabled it; see this Question for details: Why does autoReconnect=true not seem to work?