Main talk through DriverManager connection
DriverManager is a managed class of drivers.
1). The database connection can be obtained through the overloaded getconnection () method. More Convenient
2). Multiple drivers can be managed at the same time: If multiple database connections are registered, call getconnection ()
method, a different database connection is returned when the parameter passed in is different.
//1. Prepare 4 strings to connect to the database. //the full class name of the drive.String Driverclass = "Com.mysql.jdbc.Driver"; //JDBC URLString Jdbcurl = "Jdbc:mysql:///test"; //UserString user = "root"; //PasswordString password = "1230"; //2. Load the database driver (the corresponding Driver implementation class has a registered-driven static code block.)Class.forName (Driverclass); //3. Get the database connection through the DriverManager getconnection () method.Connection Connection =drivermanager.getconnection (jdbcurl, user, password); System.out.println (connection);
Further encapsulation 1) parameters extracted into the file
2) encapsulation into the method
PublicConnection getconnection ()throwsexception{//1. Prepare 4 strings to connect to the database. //1). Create a Properties objectProperties Properties =NewProperties (); //2). Gets the input stream corresponding to the jdbc.properties, src/jdbc.properties InputStream in = This.getclass (). getClassLoader (). getResourceAsStream("jdbc.properties"); //3). Load 2) corresponding input streamproperties.load (in); //4). Specifically determine the user, password, etc. 4 strings. String user = Properties.getproperty ("User"); String Password= Properties.getproperty ("Password"); String Jdbcurl= Properties.getproperty ("Jdbcurl"); String Driver= Properties.getproperty ("Driver"); //2. Load the database driver (the corresponding Driver implementation class has a registered-driven static code block.)Class.forName (driver); //3. Get the database connection through the DriverManager getconnection () method. returndrivermanager.getconnection (jdbcurl, user, password); }
Src/jdbc.properties
#driver =oracle.jdbc.driver.oracledriver#jdbcurl=jdbc:oracle:thin: @localhost: 1521:orcl#user=scott#password= javadriver=com.mysql.jdbc.driverjdbcurl=jdbc:mysql://localhost:3306/atguiguuser=rootpassword=1230
JDBC (1)--Get a database connection