Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class MySQLAccess {
- private Connection connect = null;
- private Statement statement = null;
- private PreparedStatement preparedStatement = null;
- private ResultSet resultSet = null;
- public String getResultSet() throws SQLException {
- resultSet = statement.executeQuery("select * from examen.material");
- return writeResultSet(resultSet);
- }
- public void inserare(String model, String culoare, String lungime) throws Exception {
- preparedStatement = connect
- .prepareStatement("insert into examen.material values (default, ?, ?, ?)");
- preparedStatement.setString(1, model);
- preparedStatement.setString(2, culoare);
- preparedStatement.setString(3, lungime);
- preparedStatement.executeUpdate();
- }
- public void readDataBase() throws Exception {
- try {
- // Incarca driverul MYSQL
- Class.forName("com.mysql.jdbc.Driver");
- // Creeaza conexiunea cu baza de data
- connect = DriverManager.getConnection("jdbc:mysql://localhost/examen?" + "user=root&password=");
- // Statementurile ne ajuta sa facem query
- statement = connect.createStatement();
- // Afisam toata baza de date
- resultSet = statement.executeQuery("select * from examen.material");
- writeResultSet(resultSet);
- System.out.println("---------------------------------------");
- } catch (Exception e) {
- throw e;
- } finally {
- close();
- }
- }
- private String writeResultSet(ResultSet resultSet) throws SQLException {
- // ResultSet is initially before the first data set
- String str = "NU AFISEAZA NIMIC";
- while (resultSet.next()) {
- // It is possible to get the columns via name
- // also possible to get the columns via the column number
- // which starts at 1
- // e.g. resultSet.getSTring(2);
- String model = resultSet.getString("model");
- String culoare = resultSet.getString("culoare");
- String lungime = resultSet.getString("lungime");
- str = str + ("\nModel: " + model + "Culoare: " + culoare + "Lungime: " + lungime);
- }
- return str;
- }
- // You need to close the resultSet
- private void close() {
- try {
- if (resultSet != null) {
- resultSet.close();
- }
- if (statement != null) {
- statement.close();
- }
- if (connect != null) {
- connect.close();
- }
- } catch (Exception e) {
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement