1、JDBC中所要用的包几乎都在import java.sql.*;中;
import java.sql.*;
在项目中导入Oracel或者是MySQL包和装载驱动:
项目的ClassPath和系统的ClassPath建议放在ClassPath,如果放在系统的ClassPath中如果版本不同,可能干扰系统中的不同的项目,放在项目下,降低项目之间的耦合性;
2、加载驱动(类):
装载Oracle驱动:
Class.forName("oracle.jdbc.driver.OracleDriver");
装载MySQL驱动:
Class.forName("com.mysql.jdbc.Driver");
3、建立连接(获取Connection对象):
建立Oracle连接:
Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/datebase","user","password");
建立MySQL连接:
Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/datebase","user","password");
4、测试连接:
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) throws Exception {
//Class.forName("com.mysql.jdbc.Driver");
long start = System.currentTimeMillis();
new com.mysql.jdbc.Driver();
//Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/datebase","user","password");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/martin","root","admin");
//Connection conn = DriverManager.getConnection("jdbc:oracle:thin@host:port:datebase","user","password");
//System.out.println(conn);
System.out.println(conn);
long end = System.currentTimeMillis();
System.out.println("建立连接耗时: "+(end - start));
}
}