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.
Related
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.
I'm currently working on this dynamic web project. I have a database and table that I've created in Oracle.
What I need to do right now is have this table connected to my project so that I can retrieve the data from there.
I read that I will need a JDBC driver downloaded and I found it here
But, it's not clear which one is the right one to download and where should I place it after that? in connection pool through admin console?
all toturials I see are related to mySql even this one:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";
// Database credentials
static final String USER = "root";
static final String PASS = "password";
How can I use the same thing for oracle?
It is a example, how to connect to DB and to retrieve data from DB. I hope it is useful for you. Don't forget about try catch finally.
Read this topic.
Closing Database Connections in Java
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#127.0.0.1:1521:xe"; //127.0.0.1 = localhost, 1521 = standard port, xe - DB name
String user = "root";
String password = "password";
Connection con = DriverManager.getConnection(url, user, password);
//To create sql query
PreparedStatement preparedStatement = con.prepareStatement("SELECT * FROM person");
//Response of your sql query
ResultSet resultSet = preparedStatement.executeQuery();
//For example you have table (Int id, String firstName, String lastName )
while(resultSet.next()){
//Prepare your data with your program logic....
int id = resultSet.getInt(1);
String firstName = resultSet.getString(2);
String lastName = resultSet.getString(3);
Person p = new Person(id, firstName, lastName);
}
Can you check the JDK version and the JDBC driver version that you are using? Both should be compatible. Check out the FAQ for more information.
I'm fairly new to database management. I'm just trying to connect to the database and retrieve and display a table in the command prompt. The database is not on my computer. I am fairly certain that the url is the problem. The code:
import java.io.*;
import java.sql.*;
class transfer{
//driver and DB URLs
final static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
final static String DB_SQL = "jdbc:microsoft:sqlserver://localhost:1433;" + "database=DataDB;" + "user=sa;" + "password=1234";
//Database Username and password
final static String user1 = "sa";
final static String pass1 = "1234";
static ResultSet rs;
public static void main(String args[]) throws SQLException, ClassNotFoundException{
Connection conn_sql = null;
Statement stmt_sql = null;
//Statement stmt_ora = null;
//Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Open Connection
System.out.println("Connecting to SQL database...");
conn_sql = DriverManager.getConnection(DB_SQL, user1, pass1);
//Execute Query
String sql_query;
System.out.println("Creating statement for SQL...");
stmt_sql = conn_sql.createStatement();
sql_query = "Select * from attendancesummary";
rs = stmt_sql.executeQuery(sql_query);
System.out.println("SQL table details");
System.out.println("Creating statement for SQL...");
while(rs.next()){
//Retrieve data
int cno = rs.getInt("CardNo");
int in_time = rs.getInt("entry");
int out_time = rs.getInt("Exittm");
String name = rs.getString("Name");
int date = rs.getInt("TrDate");
//Display data
System.out.print("Employee ID: "+cno);
System.out.print("\tName: "+name);
System.out.print("\tDate:"+date);
System.out.print("\tEntry: "+in_time);
System.out.print("\tExit: "+out_time);
}
}
}
The database name is DataDB and the table that I want to retrieve and display is attendancesummary. I have set my path as "C:\Program Files\Java\jdk1.8.0_11\bin";"C:\Program Files\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc4.jar"
The code compiles fine.. but when I run it, I get the following error:
Exception in thread "main" java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run
at java.net.URLClassLoader$1.run
at java.security.AccessController.doPrivileged
at java.net.URLClassLoader.findClass
at java.lang.ClassLoader.loadClass
at sun.misc.Launcher$AppClassLoader.loadClass
at java.lang.ClassLoader.loadClass
at java.lang.Class.forname0
at java.lang.Class.forname
at transfer.main
I am truly lost. Any help would be appreciated!
It means that sqljdbc4.jar is missing from your CLASSPATH while running the code. If you are running this from command line then add the path to sqljdbc4.jar in -cp switch of java command.
If you are running from eclipse, then add sqljdbc4.jar in your build path.
Add sqljdbc4.jar in your classpath.
If you are using Eclipse then you can right click on project -> properties -> java build path.
Go to libraries and click on add external jar.
Then add the jdbc driver jar.
Hope this helps.
You have to add the JDBC driver to your project class path: example if you are using Eclipse put the jar in the 'lib' folder
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
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);
}
}
}