Advertisement
Guest User

Untitled

a guest
Dec 15th, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.Scanner;
  3.  
  4. public class ConnectionExample {
  5. public static void main(String[] args) {
  6. Scanner sc = new Scanner(System.in);
  7.  
  8. // a port is a 4 digit number, if you don't know what to enter, then enter 8080
  9. System.out.print("Enter a port: ");
  10. String url = "jdbc:mysql://localhost:" + sc.next();
  11.  
  12. // you first need to create a database manually and then enter its name, see the comment section
  13. System.out.print("Database name: ");
  14. String dbname = sc.next();
  15.  
  16. // enter the username who has access to the DB, see the comment section
  17. System.out.print("Username: ");
  18. String username = sc.next();
  19.  
  20. // enter the password that you configured while creating the database
  21. System.out.print("Password: ");
  22. String password = sc.next();
  23.  
  24. // the driver is the name of the class that is used to establish a connection with the database, it is different for
  25. // different database management system. For MySQL it is the following:
  26. String driver = "com.mysql.jdbc.Driver";
  27.  
  28. // here we actually connect to the databse, given the above information
  29. try {
  30. Class.forName(drive).newInstance();
  31. Connection conn = DriverManager.getConnection(url + dbname, username, password);
  32.  
  33. /*
  34. Now that you have obtained a connection, you can do several things like insert, delete, etc.
  35. The logic of your database use go here. Once you are done, the last command closes the connection.
  36. */
  37.  
  38. conn.close();
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement