Java连接数据库的几种方法
*说明
1.以MySQL数据库为例
2.分为四个步骤:
建立数据库连接,
向数据库中提交sql
处理数据库返回的结果
关闭数据库连接
一:JDBC
1.建立数据库连接
只需要两步,注册数据库的驱动程序,然后创建数据库连接
示例代码:
String url="jdbc:mysql://localhost:3306/test";
String Driver="com.mysql.jdbc.Driver";
String username="root";
String password="123456";
Class.forName(Driver);
Connection conn=DriverManager.getConnection(url,username,password);
方法一
String url="jdbc:mysql://localhost:3306/test";
String username="root";
String password="123456";newcom.mysql.jdbc.Driver();
Connection conn=DriverManager.getConnection(url,username,password);
方法二
首先通过java.lang.Class类的forName()静态方法动态加载MySQL驱动程序的类,这个类会自动在DriverManager中进行注册,然后通过DriverManager获得Connection类型的对象
2.通过数据库连接池,效率高
原理就是通过修改Tomcat服务器conf目录下的context.xml文件来进行配置的
配置的代码:
WEB-INF/web.xml
context.xml
通过数据源对象获取连接池中的数据库连接对象
Context context=newInitialContext();
DataSource ds=(DataSource) context.lookup("java:/comp/env/jdbc/mysql");
Connection conn=ds.getConnection();
View Code
3.其他步骤在后面讲
二.以后补充