Background
[wp_ad_camp_3]
This article demonstrates how to connect to MySQL using JDBC.
Software Environment
- Windows 7 Professional SP1
- MariaDB 10.0.14
- mariadb-10.0.14-win32.exe
- MariaDB Java client 1.1.7
- mariadb-java-client-1.1.7.jar
The Codes
[wp_ad_camp_5]
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | package com.turreta.mysql; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Connection; import java.sql.DriverManager; public class MariaDBJdbcSample { public static void main(String... a) { Connection connection = null; PreparedStatement stmt = null; PreparedStatement stmtI = null; ResultSet rs = null; try { Class.forName("org.mariadb.jdbc.Driver"); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3307/turretadb", "root", "password"); stmt = connection .prepareStatement("SELECT lname, fname, mname FROM PERSON"); rs = stmt.executeQuery(); while (rs.next()) { System.out.println("LASTNAME: " + rs.getString("lname")); System.out.println("MIDDLENAME: " + rs.getString("mname")); System.out.println("FIRSTNAME: " + rs.getString("fname")); System.out .println("================================================"); } connection.setAutoCommit(false); stmtI = connection .prepareStatement("INSERT INTO PERSON (lname, fname, mname) VALUES (?, ?, ?)"); for (int i = 0; i < 10; i++) { stmtI.setString(1, "DOE"); stmtI.setString(2, "ANONYMOUS"); stmtI.setString(3, "JANE"); stmtI.executeUpdate(); } connection.commit(); connection.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } |
Download the Project
https://www.dropbox.com/s/vel3adj4g6tq8t0/turreta%20-%20database%20-%20mariadbjdbc.zip?dl=0
[wp_ad_camp_4]