· 7 years ago · Jan 19, 2019, 10:26 AM
1package com.company;
2
3import java.sql.*;
4
5/**
6 * Created by philos_ofas on 25/01/2017.
7 */
8public class DBConnection {
9
10
11 public Statement getConnection() throws SQLException, ClassNotFoundException {
12 Connection conn = connectTODB();
13 Statement statement = null;
14 statement = conn.createStatement();
15 String sql = "CREATE TABLE IF NOT EXISTS Login (id INT,"
16 + "UserName VARCHAR(100),"
17 + "Password VARCHAR(100),"
18 + "FirstName VARCHAR(50),"
19 + "LastName VARCHAR(50),"
20 + "Address VARCHAR(150),"
21 + "PostalCode Varchar (50),"
22 + "BirthDate Date);";
23 statement.executeUpdate(sql);
24
25 System.out.println("Sukurta Lenta Login");
26
27 String insertDataSql = "INSERT INTO Login (id, UserName, Password, FirstName, LastName, Address, PostalCode, BirthDate)\n" +
28 "VALUES ('1234','philos_ofas','pass','Aurimas', 'Kraulaidys', 'zygio g. Vilnius','8345', '2014-11-01');";
29 statement.executeUpdate(insertDataSql);
30
31 System.out.println("Įterpta eilute i Lenta Login");
32
33 String SelectAll = "Select * from Login;";
34 ResultSet resultSet = statement.executeQuery(SelectAll);
35
36 while (resultSet.next()) {
37 String userValue = resultSet.getString("UserName");
38 String passwordValue = resultSet.getString("Password");
39 String firstNameValue = resultSet.getString("FirstName");
40 Date BirthDateValue = resultSet.getDate("BirthDate");
41 System.out.println("Some info after Select query: UserName " + userValue + " password: "
42 + passwordValue + " BirthDate: " + BirthDateValue );
43 }
44
45 return statement;
46 }
47
48
49 private Connection connectTODB() throws ClassNotFoundException, SQLException {
50 Connection connection = null;
51 Class.forName("com.mysql.jdbc.Driver");
52 String url = "jdbc:mysql://localhost:3306/";
53 String dbName = "CarRental";
54 String driver = "com.mysql.jdbc.Driver";
55 String userName = "root";
56 String password = "pass";
57 connection = (Connection) DriverManager.getConnection(url + dbName +"?"+ "user=" +userName + "&password="+ password);
58 System.err.println("Connected to database");
59 return connection;
60 }
61
62
63
64}