First In your POM file add the following dependency.
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.17</version> <type>jar</type> <scope>compile</scope> </dependency>
Then From your java application you can check the Jdbc connection.In my application i have database called java_form and table called user_details.
In here i have First check the database connection.And next method insert data to database. Then Retrieve data from database after all close the connection.
public class DataBaseConnectivity { Connection connection; /** * Connect database * @return */ public boolean connect_database() { boolean check_connection = false; String database_Url= "jdbc:mysql://localhost/java_form"; String database_Class= "com.mysql.jdbc.Driver"; String username = "root"; String password = ""; try { Class.forName(database_Class); connection = DriverManager.getConnection(database_Url, username, password); if (connection != null) { check_connection = true; } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return check_connection; } /** * Insert DATA to table * @param uId * @return */ public boolean insert_uId(String uId) { String query = "INSERT INTO user_details (uID)VALUES (" + uId + ")"; Statement statement = null; try { statement = connection.createStatement(); int resultSet = statement.executeUpdate(query); System.out.println("UID added to database"); } catch (SQLException e) { e.printStackTrace(); } return true; } /** * Retrive data from table * @return */ public boolean retrive_Data() { String query = "Select uID from user_details"; try { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { String tableName = resultSet.getString(1); System.out.println("UID value : " + tableName); } } catch (SQLException e) { e.printStackTrace(); } return true; } }
No comments:
Post a Comment