注意点:
1、所有和数据库相关的(jdbc)包都是java.sql.*;
2、将项目所需的jar包统一复制到web-inf/lib文件夹中。
一:sqlsever数据库
package dbcon;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConn {
public Connection getCon(){
//声明连接对象 Connection con = null;
try {
//加载驱动
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//获得数据库的连接
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=db_errorsystem", "sa", "sa");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//返回值
return con;
}
/**
* @param args
*/
//测试是否连接成功
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new DBConn().getCon());
}
}
二:MySQL数据库
package dbcon;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
public Connection getConnection(){
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "123456");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
}
三:Oracle数据库
package cn.com.systop.l03.dbconnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 数据库连接类
* @author Administrator
*
*/
public class DBConnection {
//数据库连接字符串
private final static String URL="jdbc:oracle:thin:@localhost:1521:xe";
//数据库登录用户名 private final static String USERNAME = "scott";
//登录密码
private final static String PASSWORD = "tiger";
/**
* 获得数据库连接
* @return 数据库连接对象
*/
public static Connection getConnection(){
Connection con = null;
try {
//加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//获得数据库连接
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
}
各个数据库的驱动jar包,连接sql 2008需要用sqljdbc4.jar;
jar包链接:http://pan.baidu.com/s/1c0hED0k
原文:http://www.cnblogs.com/sayy/p/4014656.html