Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- public class Main {
- // CRUD - Create Read Update Delete
- // SQL ordene: SELECT = read, UPDATE = update, INSERT = create og DELETE = delete
- public static void main(String[] args){
- String dbURL = "jdbc:mysql://localhost:3306/sampledb"; // eller student db
- String username = "root";
- String password = "4Chan2k!";
- try {
- Connection conn = DriverManager.getConnection(dbURL, username, password);
- if (conn != null) {
- System.out.println("Connected");
- //insertUser(conn);
- //deleteUser(conn);
- //listUsers(conn);
- updateUser(conn);
- }
- } catch (SQLException ex) {
- ex.printStackTrace();
- }
- }
- public static void insertUser(Connection conn){
- String sql = "INSERT INTO Users (username, password, fullname, email) VALUES (?, ?, ?, ?)";
- PreparedStatement statement = null;
- try {
- statement = conn.prepareStatement(sql);
- statement.setString(1, "M");
- statement.setString(2, "secretpa2ss");
- statement.setString(3, "Joakim Sælemyr");
- statement.setString(4, "bill.gates@microsoft.com");
- int rowsInserted = statement.executeUpdate();
- if (rowsInserted > 0) {
- System.out.println("A new user was inserted successfully!");
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public static void deleteUser(Connection conn){
- String sql = "DELETE FROM SampleDB.users WHERE user_id=11";
- PreparedStatement statement = null;
- try {
- statement = conn.prepareStatement(sql);
- int rowsInserted = statement.executeUpdate();
- System.out.println("ADELTELTLELELELTLETKELKTLEKTLEKLE! " + rowsInserted);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public static void listUsers(Connection conn){
- String sql = "SELECT * FROM Users";
- try{
- Statement statement = conn.createStatement();
- ResultSet result = statement.executeQuery(sql);
- int count = 0;
- while (result.next()){
- String name = result.getString(2);
- String pass = result.getString(3);
- String fullname = result.getString("fullname");
- String email = result.getString("email");
- String output = "User #%d: %s - %s - %s - %s";
- System.out.println(String.format(output, ++count, name, pass, fullname, email));
- }
- } catch(SQLException e){
- System.out.println("WAT DA FEK");
- }
- }
- public static void updateUser(Connection conn){
- try{
- String sql = "UPDATE Users SET password=?, fullname=?, email=? WHERE username=?";
- PreparedStatement statement = conn.prepareStatement(sql);
- statement.setString(1, "MORTEN2k");
- statement.setString(2, "Morten Amundsen");
- statement.setString(3, "Mortenamundsen@microsoft.com");
- statement.setString(4, "morten15");
- int rowsUpdated = statement.executeUpdate();
- if (rowsUpdated > 0) {
- System.out.println("An existing user was updated successfully!");
- }
- } catch(SQLException e){
- System.out.println("A FEKK");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement