Guest User

SQL connect

a guest
Dec 7th, 2017
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.Properties;
  3. import java.sql.DriverManager;
  4.  
  5. public class Main {
  6.  
  7. public static void main(String[] args) throws SQLException, ClassNotFoundException {
  8. //Load MySQL driver
  9. String driver = "com.mysql.jdbc.Driver";
  10. Class.forName(driver);
  11.  
  12. Connection con = getConnection();
  13. viewTable(con, "SpelRsi");
  14.  
  15. }
  16. public static void viewTable(Connection con, String dbName)
  17. throws SQLException {
  18.  
  19. Statement stmt = null;
  20. String query = "SELECT beskrivning FROM Produkt";
  21. try {
  22. stmt = con.createStatement();
  23. ResultSet rs = stmt.executeQuery(query);
  24. while (rs.next()) {
  25. String beskrivning = rs.getString("beskrivning");
  26. System.out.println(beskrivning + "\t");
  27. }
  28. }finally {
  29. if (stmt != null) { stmt.close(); }
  30. }
  31. }
  32.  
  33. public static Connection getConnection() throws SQLException {
  34.  
  35. Connection con = null;
  36. Properties connectionProps = new Properties();
  37. connectionProps.put("user", "root");
  38. connectionProps.put("password", "Nicock");
  39.  
  40. con = DriverManager.getConnection(
  41. "jdbc:mysql://localhost:3306/SpelRsi",
  42. connectionProps);
  43. System.out.println("Connected to database");
  44. return con;
  45. }
  46.  
  47. }
Add Comment
Please, Sign In to add comment