Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- import java.util.Scanner;
- public class ConnectionExample {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- // a port is a 4 digit number, if you don't know what to enter, then enter 8080
- System.out.print("Enter a port: ");
- String url = "jdbc:mysql://localhost:" + sc.next();
- // you first need to create a database manually and then enter its name, see the comment section
- System.out.print("Database name: ");
- String dbname = sc.next();
- // enter the username who has access to the DB, see the comment section
- System.out.print("Username: ");
- String username = sc.next();
- // enter the password that you configured while creating the database
- System.out.print("Password: ");
- String password = sc.next();
- // the driver is the name of the class that is used to establish a connection with the database, it is different for
- // different database management system. For MySQL it is the following:
- String driver = "com.mysql.jdbc.Driver";
- // here we actually connect to the databse, given the above information
- try {
- Class.forName(drive).newInstance();
- Connection conn = DriverManager.getConnection(url + dbname, username, password);
- /*
- Now that you have obtained a connection, you can do several things like insert, delete, etc.
- The logic of your database use go here. Once you are done, the last command closes the connection.
- */
- conn.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement