1、这里介绍java代码连接常用数据库的方式,数据库包括MySQL、Sybase、Oracle、SqlServer,连接数据库都是需要在工程里添加jar包加载驱动的,这几个jar包我整理好放在csdn资源中了,下载地址:http://download.csdn.net/detail/wangduanqing5945/7004093 2、
Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/boxmanager", "username", "password"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }
try { String driver = "com.sybase.jdbc3.jdbc.SybDriver"; Class.forName(driver).newInstance(); String url = "jdbc:sybase:Tds:192.168.100.252:4500/myDB";// // myDB为你的数据库名 Properties sysProps = System.getProperties(); sysProps.put("user", username); // 设置数据库访问用户名 sysProps.put("password", password); // 密码 connection = DriverManager.getConnection(url, sysProps); } catch (Exception e) { e.printStackTrace(); }
// 得到连接 Connection ct = null; try { // 加载驱动 Class.forName("oracle.jdbc.driver.OracleDriver"); ct = DriverManager.getConnection( "jdbc:oracle:thin:@127.0.0.1:1521:simlink", "your username", "your pwd"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }
String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; String dbURL = "jdbc:microsoft:sqlserver://localhost:1433;databasename=li"; // 1433是数据库的端口,"li"是你的数据库名称 String userName = "sa"; // sa是数据库的超级用户,最好不要换别的名字,权限问题 String userPwd = "123456"; // sa的密码 Connection dbConn = null; try { Class.forName(driverName).newInstance(); dbConn = DriverManager.getConnection(dbURL, userName, userPwd); System.out.println("连接成功!"); } catch (Exception e) { e.printStackTrace(); }