JDBC 3 (web basic learning note 9) and jdbc learning note
1. JDBC programming steps
2. Add database information to the resource file
// (1) Use Class. forName to import drive Class. forName ("oracle. jdbc. driver. oracleDriver "); // (2) use DriverManager. getconnection (url, user name, password) Connection creation return type is Connection type conn = DriverManager. getConnection ("jdbc: oracle: thin :@ localhost: 1521: orcl", "news", "news ");
Put the above information into the resource file and reuse it
2.1 create a resource file
Database. properties
jdbc.driver=oracle.jdbc.driver.OracleDriverjdbc.url=jdbc:oracle:thin:@localhost:1521:orcljdbc.uname=newsjdbc.upwd=news
2.2 create a class for managing this resource file
ConfigManager. class
Package pb. until; import java. io. IOException; import java. io. inputStream; import java. util. properties; public class ConfigManager {// declare the static variable private static ConfigManager confingManager; // declare the static variable Properties private static Properties properties; private ConfigManager () {// obtain the file path String configfile = "database. properties "; // declare the new Properties object properties = new Properties (); InputStream is = ConfigManager. class. getClassLoader (). getResourceAsStream (configfile); // use the load method to read the file try {properties. load (is); is. close ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}}// create a single instance object public static ConfigManager getintance () {if (confingManager = null) {confingManager = new ConfigManager ();} return confingManager ;} public String getvalue (String key) {return properties. getProperty (key );}}
2.3 replace the original database information in the JAVA class
String driver = ConfigManager. getintance (). getvalue ("jdbc. driver "); String url = ConfigManager. getintance (). getvalue ("jdbc. url "); String uname = ConfigManager. getintance (). getvalue ("jdbc. uname "); String upwd = ConfigManager. getintance (). getvalue ("jdbc. upwd "); try {// (1) Use Class. forName to import drive Class. forName (driver); // (2) use DriverManager. getconnection (url, user name, password) Connection creation return type is Connection type conn = DriverManager. getConnection (url, uname, upwd );