以mysql数据库为例
1、加载驱动
public class TestDatabase { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("加载驱动成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }运行结果
加载驱动成功
或者:
public class TestDatabase { private static String dbname="com.mysql.jdbc.Driver"; public static void main(String[] args) { try { Class.forName("dbname"); System.out.println("加载驱动成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
数据库连接
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class TestDatabase { public static void main(String[] args) { Connection con=null; try { Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/school"; con=DriverManager.getConnection(url,"root","123456"); System.out.println("数据库连接成功"); System.out.println("加载驱动成功"); } catch (Exception e) { e.printStackTrace(); }finally{ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
运行结果
数据库连接成功 加载驱动成功
或者:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class TestDatabase { private static String dbname="com.mysql.jdbc.Driver"; private static String dburl="jdbc:mysql://localhost:3306/school"; private static String username="root"; private static String password="123456"; public static void main(String[] args) { Connection con=null; try { Class.forName(dbname); con=DriverManager.getConnection(dburl,username,password); System.out.println("数据库连接成功"); System.out.println("加载驱动成功"); } catch (Exception e) { e.printStackTrace(); }finally{ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
或者(不建议使用):
import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; public class TestDatabase { public static void main(String[] args) { try { Properties p=new Properties(); InputStream in=new FileInputStream("./src/db.properties"); p.load(in); System.out.println("数据库连接成功"); System.out.println("加载驱动成功"); } catch (Exception e) { e.printStackTrace(); } } }
db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/school name=root password=123456
在或者(建议使用)
import java.io.InputStream; import java.util.Properties; public class TestDatabase { public static void main(String[] args) { try { Properties p=new Properties(); //获取程序运行环境的类加载器,默认加载src根目录的文件信息 ClassLoader loader=TestDatabase.class.getClassLoader(); InputStream in=loader.getResourceAsStream("db.properties"); p.load(in); System.out.println("数据库连接成功"); System.out.println("加载驱动成功"); } catch (Exception e) { e.printStackTrace(); } } }
工程目录