Hi there .Its a sample implementation of mysql connection with java
#database
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
CREATE TABLE IF NOT EXISTS `employees` ( `Id` int(11) NOT NULL, `first_name` text NOT NULL, `last_name` text NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `employees` -- INSERT INTO `employees` (`Id`, `first_name`, `last_name`) VALUES (1, 'aaaa', 'cccc'), (2, 'ssss', 'cccc'); select * from employees; |
#pom.xml
1 2 3 4 5 6 7 |
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> </dependencies> |
#main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public static void main(String[] args) { System.out.println("Hello World!"); Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // new com.mysql.jdbc.Driver(); Class.forName("com.mysql.jdbc.Driver").newInstance(); // conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase?user=testuser&password=testpassword"); String connectionUrl = "jdbc:mysql://localhost:3306/test"; String connectionUser = "root"; String connectionPassword = ""; conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM employees"); while (rs.next()) { String id = rs.getString("Id"); String firstName = rs.getString("first_name"); String lastName = rs.getString("last_name"); System.out.println("ID: " + id + ", First Name: " + firstName + ", Last Name: " + lastName); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } |