Advertisement
ticux

Untitled

Jan 28th, 2019
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package model;
  7.  
  8. /**
  9.  *
  10.  * @author ticu
  11.  */
  12. import java.sql.Connection;
  13. import java.sql.DriverManager;
  14. import java.sql.ResultSet;
  15. import java.sql.SQLException;
  16. import java.sql.Statement;
  17.  
  18. public class SQLDatabaseConnection {
  19.     private String connectionUrl = "jdbc:sqlserver://localhost;user=SA;password=Password123;database=MagicApp;";
  20.     private Statement stmt;
  21.     // Connect to your database.
  22.     // Replace server name, username, and password with your credentials
  23.     public SQLDatabaseConnection(int ID,String name){
  24.         try (Connection con = DriverManager.getConnection(connectionUrl); Statement stmt = con.createStatement();) {
  25.             String SQL = "SELECT TOP 10 * FROM Users";
  26.             String sql2 = "INSERT INTO Users VALUES ("+ID+", '"+name+"', 'Ionut', 'USA', 'email@email.dk')";
  27.             stmt.executeUpdate(sql2);// sql to insert values
  28.            
  29.             ResultSet rs = stmt.executeQuery(SQL); // retrieve a result set which we can use to iterate through it after.
  30.  
  31.             // Iterate through the data in the result set and display it.
  32.             while (rs.next()) {
  33.                 System.out.println(rs.getString("Name") + " " + rs.getString("SecondName")); //Name and SecondName are fields that actualy exist in the database
  34.                
  35.             }
  36.         } // Handle any errors that may have occurred.
  37.         catch (SQLException e) {
  38.             e.printStackTrace();
  39.         }
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement