(一)加载JDBC驱动程序,并连接数据库.JDBC对于不同的数据库的连接方法略有不同.具体如下所示.//连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码
1、DB2
Class.forName("Com.ibm.db2.jdbc.net.DB2Driver");
String url="jdbc:db2://dburl:port/DBname"
cn = DriverManager.getConnection( url, userName, password );
2、Microsoft SQLServer(microsoft)
Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver" );
cn = DriverManager.getConnection( "jdbc:microsoft:sqlserver://DBServerIP:1433;databaseName=master", userName, password );
3、Sybase(jconn2.jar)
Class.forName( "com.sybase.jdbc2.jdbc.SybDriver" );
cn = DriverManager.getConnection( "jdbc:sybase:Tds:DBServerIP:2638", userName, password);
4、MySQL(mm.mysql-3.0.2-bin.jar)
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection( "jdbc:mysql://DBServerIP:3306/myDatabaseName", userName, password );
5、PostgreSQL(pgjdbc2.jar)
Class.forName( "org.postgresql.Driver" );
cn = DriverManager.getConnection( "jdbc:postgresql://DBServerIP/myDatabaseName", userName, password );
6、Oracle(classes12.jar)
Class.forName( "oracle.jdbc.driver.OracleDriver" );
cn = DriverManager.getConnection( "jdbc:oracle:thin:@MyDbComputerNameOrIP:1521:ORCL", userName, password );
7、ODBC
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
Connection cn = DriverManager.getConnection( "jdbc:odbc:" + sDsn, userName, password );
由于我的电脑安装的是Mysql,主机IP为"192.168.137.1",数据库端口是默认的3306.故,连接到Mysql的程序为:
Class.forName("com.mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://192.168.137.1:3306/LibraryDB","user","1234");