一般数据库连接的代码如下:
//加载驱动类
try{
Class.forName(driverName);
}catch(ClassNotFoundException e){
System.out.println(e.getMessage());
}
try{
String url="XXX";
String user="XX";
String password="XXXXXX";
Connection conn=DriverManager.getConnection(url,user,password);
//执行sql动作
}catch(SQLException e){
System.out.println(e.getMessage());
}
但是不同的数据库对应的驱动器类名,数据库url是不同的。其实,现在不需要Class.forName()注册数据库的驱动也能正常使用。
* <P>Applications no longer need to explicitly load JDBC drivers using <code>Class.forName()</code>. Existing programs * which currently load JDBC drivers using <code>Class.forName()</code> will continue to work without * modification.
也就是说:应用程序不再需要使用 Class.forName() 显式地加载 JDBC 驱动程序。当前使用 Class.forName() 加载 JDBC 驱动程序的现有程序将在不作修改的情况下继续工作。
1,mysql
//mysql版本不同 驱动类不同 //低版本 Class.forName("com.mysql.jdbc.Driver"); //高版本 Class.forName("com.mysql.cj.jdbc.Driver"); //数据库url 配置文件xml和代码中的内容不同 即&表示方式不同 //xml <property name="DB.URL" value="jdbc:mysql://${DB.HOST}:${DB.PORT}/${DB.SID}?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT"/> //代码中 其中localhost指本机,3306指mysql默认端口,testdb指数据库名 String url="jdbc:mysql://localhost:3306/testdb?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT";
2,SQL Server
//驱动类 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //数据库url //sql server 2000 String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=testdb"; //sql server 2005及以上 String url="jdbc:sqlserver://localhost:1433;DatabaseName=testdb"; //上面都是sql server 身份验证登录,而下面是Windows身份验证,而1368是自定义端口 String url="jdbc:sqlserver://localhost:1368;DatabaseName=testdb:integratedSecurity=true";
3,Oracle
//驱动类 Class.forName("oracle.jdbc.driver.OracleDriver"); //数据库url jdbc:oracle:thin:@//<host>:<port>/ServiceName // 或 jdbc:oracle:thin:@<host>:<port>:<SID> String url="jdbc:oracle:thin:@//localhost:1521/orcl"; String url="jdbc:oracle:thin:@localhost:1521:orcl";
posted on
浙公网安备 33010602011771号