The username, password, and connection URL of the database can be stored in an independent file when JDBC is used to establish a database connection. For example:
Put the property file in the directory/test. Its content is:
- Drivers = com. Microsoft. JDBC. sqlserver. sqlserverdriver
- Url = JDBC: Microsoft: sqlserver: // localhost: 1433; databasename = studentmanager
- User = sa
- Password = wang411dong516
Dbconnection. Java:
- /**
- * Load the database driver through the attribute file to establish a database connection
- */
- Import java. SQL. sqlexception;
- Import java. SQL. connection;
- Import java. SQL. drivermanager;
- Import java. util. properties;
- Import java. Io. fileinputstream;
- Import java. Io. ioexception;
- Import java. Io. filenotfoundexception;
- Public class dbconnection
- {
- Private string URL; // Database URL
- Private string username; // The username used to log on to the database.
- Private string password; // User Password
- /**
- * Return a connection to the database. In a system or class, database operations are often performed.
- * The database connection is used as a separate method.
- */
- Public connection getconnection ()
- {
- Getproperty ();
- Connection con = NULL;
- Try
- {
- Con = drivermanager. getconnection (URL, username, password );
- }
- Catch (sqlexception E)
- {
- E. printstacktrace ();
- }
- Return con;
- }
- /**
- * Read the property configuration file
- */
- Private void getproperty ()
- {
- Properties prop = new properties ();
- Try
- {
- Fileinputstream in = new fileinputstream ("driver. properties ");
- Prop. Load (in );
- String driver = prop. getproperty ("drivers ");
- If (driver! = NULL)
- System. setproperty ("JDBC. Drivers", driver );
- Url = prop. getproperty ("url ");
- Username = prop. getproperty ("user ");
- Password = prop. getproperty ("password ");
- }
- Catch (filenotfoundexception E)
- {
- E. printstacktrace ();
- }
- Catch (ioexception E)
- {
- E. printstacktrace ();
- }
- }
- }