Post date: Mar 21, 2020 4:7:1 PM
Using Apache Netbeans 11.3.
XAMPP Control Panel V3.2.2.
I decided to try a simple HelloWorld on my newly reinstalled Java development.. I decided to try https://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm .So I found the following problems.
netbeans didn't appear to have the mysql jdbc connector.In order to get it, I went to https://dev.mysql.com/downloads/connector/j/ and I downloaded the bottom link. Actually, I was so confused I downloaded both and latter read somewhere only the bottom link is needed. After installing, you will find a jar file C:\Program Files (x86)\MySQL\Connector J 8.0/mysql-connector-java-8.0.19.jar which you can use.
go to the netbeans project navigator on the upper left and click on the Services tab. Open the Database node and open the Drivers folder under it. Right click on the MySQL (Connector/J driver) and select Customize. A popup will open and make sure the large window titled Driver File(s) has a path pointing to the jar file in 1. above.
Now go back to the code and change the JDBC_DRIVER to "com.mysql.cj.jdbc.Driver"
Change the DB_URL to "jdbc:mysql://localhost:3306/EMP?serverTimezone=SST". My timezone is SST Singapore Standard Time. Find yours.
Run.
package firstexample;
import java.sql.*;
/**
*
* @author Lenovo
*/
public class FirstExample {
/**
* @param args the command line arguments
*/
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/EMP?serverTimezone=SST";
static final String USER = "XXXXXXXX";
static final String PASS = "XXXXXXXX";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", first: " + first);
System.out.println(", last: " + last);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt!=null)
stmt.close();
} catch (SQLException se) {
// nothing we can do
}
try {
if (conn!=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("GoodBye!");
}
}
.