1.导入jar包
2.编写properties文件
-
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/newsmanagersystem name=root password=root
- 编写类加载器(提供公共的方法)
/** * 得到驱动 database.properties中的配置 * */ public class GetDirver { private static Properties pro=null; //静态代码块 static{ pro=new Properties(); InputStream in =GetDirver.class.getClassLoader().getResourceAsStream("database.properties"); try { pro.load(in);//加载驱动 } catch (IOException e) { System.out.println("加载驱动错误"); } } public static String getDirver(String name){ String driver=pro.getProperty(name);//得到database.properties中的数据 return driver; } }
- 建立连接(得到Connection)
public class ServerDaoUtil { private static String driver = GetDirver.getDirver("driver"); private static String url = GetDirver.getDirver("url"); private static String name = GetDirver.getDirver("name"); private static String password =GetDirver.getDirver("password"); private static Connection conn = null;// 建立空的连接 protected PreparedStatement psta = null; public static Connection getConnection() { // 使用传统的jdbc的方式连接数据库 try { Class.forName(driver); try { conn =DriverManager.getConnection(url, name, password); } catch(SQLException e) { System.out.println("得到连接失败"); } } catch(ClassNotFoundException e) { System.out.println("加载驱动失败"); // 类加载器加载驱动 } return conn; } }