This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 9 years ago.
I'm just trying to display the current status of mysql server by using the following code.
public static void main(String[] args) throws Exception {
String dbURL = "jdbc:mysql://Localhost:3306";
String username ="root";
String password = "trace";
Connection dbCon = null;
Statement stmt = null;
ResultSet rs = null;
String query ="SHOW GLOBAL STATUS";
Class.forName("com.mysql.jdbc.Driver").newInstance();
dbCon = DriverManager.getConnection(dbURL, username, password);
stmt = dbCon.prepareStatement(query);
rs = stmt.executeQuery(query);
System.out.println(rs);
while(rs.next())
{
String Counter = rs.getString(1);
int val=rs.getInt(2);
System.out.print("Counter Name : " + Counter);
System.out.print("--- Value : " + val);
}
}
But I get this error:
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.
How can i solve this?
You are creating connection with your mysql and didn't mentioned database name
jdbc:mysql://Localhost:3306
it should be defined as
jdbc:mysql://Localhost:3306/test
it might solve your problem
Related
This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 3 years ago.
The code below is exactly the same from a YouTube video, but it does not work for me. The expected output is to printout "connected" to the system, which means that JDBC is successfully connected to the database. But I get this error:
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.
Here is my code:
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Controller {
private static final String username = "root";
private static final String password = "";
private static final String connection = "jdbc:mysql://localhost/hello";
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection(connection, username, password);
System.out.println("Connected");
}
catch (SQLException se) {
System.err.println(se);
}
}
}
I've added the JDBC successfully as a library, exactly like the video showed but it doesn't work. I saw similar questions on Stack Overflow but none of them solved my problem. Any help will be appreciated, thanks!
JDBC version: mysql-connector-java-5.1.47-bin.jar
Link failure means DB is not reachable, Kindly confirm your DB host,
port, username and password. If everything is correct, kindly confirm
DB server is running and has yet to hit max connection limit.
and you are using JDBC jar file, this may be corrupted. so check it and I suggest you, import JDBC using Maven
and you did not register JDBC driver. first, register it
by using Class.forName("com.mysql.jdbc.Driver"); this
here is one example for your help,
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// 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("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, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
I assumed you put the appropriate JDBC dependency in your maven file
and use com.mysql.cj.jdbc.Driver as class for newer versions of MySQL-connector
The name of the class that implements java.sql.Driver in MySQL
Connector/J has changed from com.mysql.jdbc.Driver to
com.mysql.cj.jdbc.Driver. The old class name has been deprecated.
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
I just started to work with MySQL in Java, I am trying to update existing data in my database. The main purpose is to create a counter, there will update an int in the database when an action has been done.
In this case, I am trying to update the daily_search_count by increasing the integer when the code is compiling. Below you can see a picture of my DB data:
data within the database
The code I have written is intended to increase the "daily_search_count" by 1 each time the code is running. But unfortunately I get the following error:
Exception in thread "main" java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''accounts' set 'daily_search_count' = '4' where 'id' = '1'' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1116)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1066)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1396)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1051)
at Database.main(Database.java:29)
I can't see what is wrong with my code as you can see below:
import java.sql.*;
public class Database {
public static void main(String[] args) throws Exception {
String host = "jdbc:mysql://localhost:3306/presearch";
String username = "root";
String password = "";
String query = "select * from accounts";
Connection con = DriverManager.getConnection(host, username, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
String userData = "";
while (rs.next()) {
if (rs.getInt(4) < 33) {
userData = rs.getInt(1) + " : " + rs.getString(2) + " daily search count : " + rs.getInt(4);
System.out.println(userData);
int counter = rs.getInt(4) + 1;
PreparedStatement updatexdd = con.prepareStatement("update 'accounts' set 'daily_search_count' = '" + counter + "' where 'id' = '" + rs.getInt(1) + "'");
int updatexdd_done = updatexdd.executeUpdate();
}
}
st.close();
con.close();
}
}
I hope someone can see what I am doing wrong.
Thanks in advance!
You have some problems in your code you have to avoid :
name of table and columns should not be between two quotes 'accounts'
make sure to use placeholder(?) to specify your attribute in the query with PreparedStatement
make sure to close the connection and statement in finally block instead
I note also that all you need is just one query
Your code should look like this :
public static void main(String[] args) throws Exception {
String host = "jdbc:mysql://localhost:3306/presearch";
String username = "root";
String password = "";
String query = "update accounts set daily_search_count = daily_search_count + 1 where daily_search_count < 33";
try (Connection con = DriverManager.getConnection(host, username, password);
PreparedStatement updatexdd = con.prepareStatement(query)) {
int updatexdd_done = updatexdd.executeUpdate();
}
}
In my code I use The try-with-resources Statement which support AutoCloseable and Closeable Interface which mean you don't need to close the connection or the statement.
This question already has answers here:
Cannot simply use PostgreSQL table name ("relation does not exist")
(18 answers)
Java SQL "ERROR: Relation "Table_Name" does not exist"
(4 answers)
Postgres with Java I can't insert data
(3 answers)
Java JDBC Connection with Heroku
(2 answers)
Closed 5 years ago.
I am getting following error when I try to get ResultSet:
relation "user_login" does not exist Position: 22
I have a table name User_Login but the error indicates lower case table name. I have been trying to debug it but I am unable to find out the root cause. Below is my code snippet. Please take a look.
public String execute() throws SQLException {
String returnPage = "ERROR";
Connection connection = null;
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/Dislocation", "user","pass");
String sql = "SELECT username FROM User_Login WHERE";
sql+=" username = ? AND password = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, this.getUsername());
stmt.setString(2, this.getPassword());
ResultSet resultSet = stmt.executeQuery(); // causing error
while (resultSet.next()) {
this.username = resultSet.getString(1);
this.password = resultSet.getString(2);
returnPage = "SUCCESS";
}
} catch (ClassNotFoundException ex) {
returnPage = "ERROR";
ex.getMessage();
} finally {
if (connection != null) {
connection.close();
}
}
return returnPage;
}
stack trace:
org.postgresql.util.PSQLException: ERROR: relation "user_login" does
not exist Position: 22
You must surround the table name with double quotes if it contains upper case letters:
String sql = "SELECT username FROM \"User_Login\" WHERE";
Read the documentation for details.
I could connect to Oracle XE, DB from console using the credentials (Username: HR, Password : *****). But I'm getting the error message
ORA-28000: the account got locked
when I try to establish connection from java program using JDBC.
Code:
public static void main(String args[]) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#127.0.0.1:1521:XE";
Connection con = DriverManager.getConnection(url,"USER NAME","PASSWORD");
Statement statement = con.createStatement();
ResultSet resultset = statement.executeQuery("select 'Connected' from dual");
while (resultset.next()) {
System.out.println(resultset.getString(1));
}
statement.close();
con.close();
}
How to connect to DB from this java program?
When connect using the credentials (Username : system, Password : ####) the account got connected without any issue from java program.
However, when connected using the credentials (Username: HR, Password : **) got the error message ORA-28000: the account got locked. But was able to login using these HR credentials from oracle console.
So, to get the connection from java program, did the following:
public static void main(String args[]) throws SQLException, ClassNotFoundException{
String query;
// Connect to system Database first
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#127.0.0.1:1521:XE";
Connection con = DriverManager.getConnection(url,"system","####");
Statement statement = con.createStatement();
query = "alter user HR identified by HR account unlock";
//Unlock the account
ResultSet resultset = statement.executeQuery(query);
//Connect to HR database
con = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:XE","HR","****");
statement = con.createStatement();
//Fetch all the tables in HR database
query = "select 'Connected' from dual";
resultset = statement.executeQuery(query);
//Prints records fetched
while (resultset.next()) {
System.out.println(resultset.getString(1));
}
statement.close();
con.close();
}
The HR account got unlocked and now able to execute other queries without issues :)
Just change the username to "System" instead of "HR". and that it! you will be able now to connect to your database.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Accessing Access over JDBC (using ODBC?)
I have to do this since we have an unknown amount of access databases the user can select using our program so as to process data from them.
Here is connection code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=ACCESS_FILE_PATH/FILE_NAME.mdb";
connection = DriverManager.getConnection( database ,"username","password");
I did it as the following:
first , create a db DB1.MDB which contain a table named "table1";
second, config ODBC , create DatabaseSource named "Access2000"。
import java.sql.*;
class database {
public static void main(String args[]) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:Access2000";
Connection connection=DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql="SELECT * FROM table1";
ResultSet rs = statement.executeQuery(sql);
String tt;
while (rs.next()) {
System.out.print("name:" + rs.getString("Name"));
System.out.println("age:" + rs.getString("Age"));
}
rs.close();
connection.close();
}
catch(Exception ex){
System.out.println(ex);
System.exit(0);
}
}
}